我正在尝试设置一个Rails 3应用程序来处理Devise和CanCan的用户角色。
我的关系如下
class User < ActiveRecord::Base
has_many :users_roles
has_many :roles, :through => :users_roles
end
class Role < ActiveRecord::Base
has_many :users_roles
has_many :users, :through => :users_roles
end
class UsersRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
实际上一切都运转良好。 Devise正在完美地处理身份验证。 CanCan基于ability.rb。
限制用户行为但是设置一个UsersRole我有一个荒谬的问题。
我在用户编辑页面上定义了复选框,如此。
<% for role in Role.all %>
<%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %>
<%=h role.name.camelize %>
<% end %>
<%= hidden_field_tag "user[role_ids][]", "" %>
如果我通过控制台创建UserRole,则会根据用户角色检查这些复选框。
但我无法使用这些复选框设置或更改角色!
我一直在各地 - 语法的变化,切换到HABTM和roles_mask方法,重建我的模型和控制器几次 - 都没有效果。
实际上我的问题的标题并不完全正确 - 复选框正在放
_method put
authenticity_token XGl6s1iyXJfahdgftc3df8q1ZeehMVzs3LxiQH98jGw=
commit Update
user[current_password] password
user[email] user@example.com
user[name] User Name
user[password]
user[password_confirmatio...
user[role_ids][] 1
user[role_ids][] 4
user[role_ids][]
utf8 ✓
但是这些值没有在数据库中设置。
我做错了什么?!!!
答案 0 :(得分:2)
我的猜测是你在用户模型中指定了attr_accesible,并且那里没有列出role_ids(它不应该在那里)
如果它与Controller中的update_attributes调用结合使用,那么将永远不会正确设置role_ids。
如果是这种情况,那么您应该在更新或保存之前手动设置Controller中的role_ids:
@user.role_ids = params[:user][:role_ids]
当然,我不确定是这种情况,因为您没有在用户模型中包含控制器代码或任何细节。
编辑:
相反,如果在Controller中执行@ user.update_attributes,则可以将其更改为以下内容:
#The same as update_attributes, but without the save
@user.attributes = params[:user]
# Here the role_ids get assigned manually so it does not need to be in attr_accesible
@user.role_ids = params[:user][:role_ids] if params[:user]
# And here it gets checked if the save was successfull
if @user.save
render :action => :show
else
render :action => :edit
end