简体   繁体   English

为什么我不能通过强参数更新此关联?

[英]Why can't I update this association via strong parameters?

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

您应该指示您通过role_ids子参数传递数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM