2014-03-25 78 views
0

我最近開始使用強大的參數,我不明白爲什麼我得到這個錯誤:爲什麼我無法通過強參數更新此關聯?

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"=>"[email protected]", 
    "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... | [email protected] | 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

看看http://stackoverflow.com/questions/16549382/how-to-permit-an-array-with-strong-parameters回答你的問題。它將使用strong_parameters與數組相關聯,比如你使用role_ids做什麼。 – punnie

回答

2

你應該表明你傳遞一個數組通過role_ids子參數:

params.require(:user).permit(:email, :password, :password_confirmation, {role_ids: []}) 
+0

你是那些總是想出完美答案的人之一,它啓發我很好。保持它:) – Pavan

相關問題