0

I recently started using strong parameters and I can't understand why I'm getting this error:

From: /Users/steven/Dropbox/Testivate/app/controllers/users_controller.rb @ line 21 UsersController#create:

    18: def create
    19:   @user = User.new(params.require(:user).permit(:email, :password, :password_confirmation, :role_ids))
    20:   flash[:notice] = "User successfully created" if @user.save
 => 21:   binding.pry_remote
    22:   respond_with @user
    23: end

[1] pry(#<UsersController>)> params
=> {"utf8"=>"✓",
 "user"=>
  {"email"=>"frank@example.com",
   "role_ids"=>["", "3"],
   "password"=>"password",
   "password_confirmation"=>"password"},
 "commit"=>"Submit",
 "action"=>"create",
 "controller"=>"users"}
[2] pry(#<UsersController>)> @user
+----+-----------------+-----------------+-----------------+-----------------+-----------------+------------------+
| id | crypted_pass... | password_salt   | persistence_... | email           | created_at      | updated_at       |
+----+-----------------+-----------------+-----------------+-----------------+-----------------+------------------+
| 2  | 400$8$39$6b7... | e7yG90cL7TjP... | 03054109b156... | frank@exampl... | 2014-03-25 1... | 2014-03-25 11... |
+----+-----------------+-----------------+-----------------+-----------------+-----------------+------------------+
1 row in set
[3] pry(#<UsersController>)> Role.find(3)
+----+--------+-------------------------+-------------------------+
| id | name   | created_at              | updated_at              |
+----+--------+-------------------------+-------------------------+
| 3  | random | 2014-03-25 11:40:28 UTC | 2014-03-25 11:40:28 UTC |
+----+--------+-------------------------+-------------------------+
1 row in set
[4] pry(#<UsersController>)> @user.roles
=> []

I have:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end
steven_noble
  • 4,133
  • 10
  • 44
  • 77
  • See if http://stackoverflow.com/questions/16549382/how-to-permit-an-array-with-strong-parameters answers your question. It regards using strong_parameters with arrays, such as what it seems you're doing with role_ids. – punnie Mar 25 '14 at 11:51

1 Answers1

2

You should indicate that you're passing an array through role_ids sub-parameter:

params.require(:user).permit(:email, :password, :password_confirmation, {role_ids: []})
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • You are one of those guys who always come up with perfect answers and it inspires me well.Keep it going :) – Pavan Mar 25 '14 at 11:58