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