嵌套对象带复选框 - 即使使用accepts_nested_attributes_for,也能进行批量赋值吗?

7
我认为应该有一个简单的解决方案,因为Rails 2.3具有这种新奇的嵌套表单功能。基本上,我想同时创建或更新用户并分配角色。
看起来我做得没错,但是我收到了错误警告“WARNING:Can't mass-assign these protected attributes: roles_attrributes”。
我甚至尝试将视图更改为user[permissions_attrributes][role_id],因为我认为联接表可能会让Rails感到困惑。
无论如何,您对如何实际工作有什么建议吗?
模型
class User < ActiveRecord::Base

  has_many :permissions
  has_many :roles, :through => :permissions

  accepts_nested_attributes_for :roles
  accepts_nested_attributes_for :permissions
end

从视图中摘录(请注意,我尝试并未成功地使fields_for生成我想要的内容,也许这是我的问题?)

<% for role in Role.all %>
 <%= check_box_tag( "user[roles_attrributes][id]",role.id) %>
 <%= role.rolename %>
 <br/>
<% end %>

传递过来的参数似乎是正确的:

    {"user"=>{"password_confirmation"=>"[FILTERED]", 
"roles_attrributes"=>{"id"=>"2"}, ...
解决方案:由于我的拼写错误、未使用attr_accessible、需要访问permissions_attributes以及表单略有偏差,导致问题的出现。

模型:

has_many :permissions, :dependent => :destroy
has_many :roles, :through => :permissions
accepts_nested_attributes_for :permissions
attr_accessible :permissions_attributes

视图:

    <%  Role.all(:order => "rolename ASC").each_with_index do |role,idx| %>
    <%= check_box_tag( "user[permissions_attributes][#{idx}][role_id]",role.id) %>
    <%= role.rolename %>
    <br/>
    <% end %>
2个回答

5
如果您在check_box_tag中更正属性的拼写,那么它看起来应该可以工作。
<% for role in Role.all %>
 <%= check_box_tag( "user[roles_attributes][id]",role.id) %>
 <%= role.rolename %>
 <br/>
<% end %>

好的发现!那就解释了为什么该属性无法识别 =) - Adam Alexander

3

听起来这个属性没有被标记为允许更新。你可以通过在模型类中添加以下内容来解决:

attr_accessible :roles

或者可能是:
attr_accessible :roles_attributes

如果你查看一下,可能已经有一个可以添加这个的attr_accessible调用。更多信息可以在这里找到:

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002226


据我理解,accepts_nested_attributes_for 不需要那个。无论如何,我已经尝试了两种方法,但都没有成功。 - Bill
那个错误信息肯定是由attr_protected或attr_accessible问题引起的。此外,http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for表明即使使用ANAF也需要注意这一点。可能值得更仔细地查看一下? - Adam Alexander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接