我最近开始使用强参数,我无法理解为什么我会收到此错误:
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
=> []
我有:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
答案 0 :(得分:2)
您应该指示您通过role_ids
子参数传递数组:
params.require(:user).permit(:email, :password, :password_confirmation, {role_ids: []})