Rails 3:role_mask 无法保存 - 警告:无法批量分配受保护的属性:角色
我使用 Railscasts 189 中的代码通过 Devise 实现角色,这样我就可以使用 Cancan。但是,角色不会保存到 role_mask 字段中。我的用户模型中的相关代码:
attr_accessible :email, :password, :password_confirmation, :remember_me,
:name, :about, :awards, :url, :roles_mask
ROLES = %w[admin support worker monitor visitor]
named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
end
def role_symbols
roles.map(&:to_sym)
end
在用户“新”和“编辑”的视图中,我有以下内容来显示角色的复选框:
<p>
<%= f.label :roles %><br />
<% for role in User::ROLES %>
<%= check_box_tag "user[roles][]", role, @user.roles.include?(role) %>
<%=h role.humanize %><br />
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
</p>
当我选中几个角色的复选框并点击“提交”时,我得到以下闪光: 1 个错误禁止保存该用户:
并且我从服务器收到以下错误: 警告:无法批量分配受保护的属性:角色
我已检查数据库,但 Roles_mask 字段中未保存任何内容。 Stackoverflow 中有很多关于“无法批量分配受保护属性”的问题,但它们似乎与这种情况无关。
有什么建议吗?
I'm using the code from Railscasts 189 to implement roles with Devise so I can use Cancan. However the roles are not being saved to the role_mask field. Relevant code from my user model:
attr_accessible :email, :password, :password_confirmation, :remember_me,
:name, :about, :awards, :url, :roles_mask
ROLES = %w[admin support worker monitor visitor]
named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
end
def role_symbols
roles.map(&:to_sym)
end
In the views for user "new" and "edit" I have the following to show checkboxes for the roles:
<p>
<%= f.label :roles %><br />
<% for role in User::ROLES %>
<%= check_box_tag "user[roles][]", role, @user.roles.include?(role) %>
<%=h role.humanize %><br />
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
</p>
When I check the check boxes for a couple of the roles and hit "submit", I get the following flash:
1 error prohibited this user from being saved:
And I get the following error from the server:
WARNING: Can't mass-assign protected attributes: roles
I've checked the DB and nothing gets saved in the roles_mask field. There are lots of questions in Stackoverflow about "can't mass-assign protected attributes" but they don't seem germane to this situation.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试将 :roles 添加到 attr_accessible 列表中,如下所示:
在执行此操作之前完全了解批量分配问题。
Try adding :roles to the attr_accessible list like this:
Understand completely about the mass-assignment issues before doing this.