Ruby 2 Keyword Arguments and ActionController::Parameters

ruby, ruby-on-rails, ruby-on-rails-4

Solution

Keywords arguments must be passed as hash with symbols, not strings:

class Something
  def initialize(one: nil)
  end
end

irb(main):019:0> Something.new("one" => 1)
ArgumentError: wrong number of arguments (1 for 0)

`ActionController::Parameters` inherits from `ActiveSupport::HashWithIndifferentAccess` which defaults to string keys:

a = HashWithIndifferentAccess.new(one: 1)
=> {"one"=>1}

To make it symbols you can call `symbolize_keys` method. In your case: `User.search(params.symbolize_keys)`

Problem

I have a rails 4 application that is running on ruby 2.1. I have a `User` model that looks something like ``` class User < ActiveModel::Base def self.search(query: false, active: true, **extra) # ... end end ``` As you can see in the search method I am attempting to use the new keyword arguments feature of ruby 2. The problem is that when I call this code from in my controller all values get dumped into `query`. params ``` {"action"=>"search", "controller"=>"users", query: "foobar" } ``` Please note that this is a ActionController::Parameters object and not a hash as it looks UsersController ``` def search @users = User.search(params) end ``` I feel that this is because params is a `ActionController::Parameters` object and not a hash. However even calling `to_h` on params when passing it in dumps everything into `query` instead of the expected behavior. I think this is because the keys are now strings instead of symbols. I know that I could build a new hash w/ symbols as the keys but this seems to be more trouble than it's worth. Ideas? Suggestions?

Original source