我认为应该有一个简单的解决方案来解决这个问题,因为 Rails 2.3 具有这种新奇的嵌套表单功能。基本上我想创建或更新用户并同时为他们分配角色。
似乎我做的一切都是正确的,但我收到了错误警告:无法批量分配这些受保护的属性:roles_atrributes.
我什至尝试将视图更改为 user[permissions_attrributes][role_id] 因为我认为连接表可能会让 Rails 感到困惑。
无论如何,关于这实际上应该如何运作有什么建议吗?
Model
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"}, ...
Solution我的拼写错误、未使用 attr_accessible、需要访问 Permissions_attributes 以及表单略有偏差的组合。
Model:
has_many :permissions, :dependent => :destroy
has_many :roles, :through => :permissions
accepts_nested_attributes_for :permissions
attr_accessible :permissions_attributes
View:
<% 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 %>