Rails 3.2,批量分配,动态角色?

8

我有一个Rails应用程序,其中包含一个用户模型,其中包含一个admin属性。它使用attr_accessible进行锁定。我的模型如下:

attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation
attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation, :admin, :as => :admin

这是我的用户控制器中更新方法的样子:

def update
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user], :as => current_user_role.to_sym)
    flash[:notice] = "Profile updated"
    redirect_to edit_user_url(@user)
  else
    render 'edit'
  end
end

我在应用控制器中有一个辅助方法,它以字符串形式返回角色:

def current_user_role
  @current_user_role ||= current_user.admin? ? "admin" : "default"
end
helper_method :current_user_role

我还在config/application.rb中设置了config.active_record.whitelist_attributes = true
我已验证current_user_role方法根据当前用户的管理员状态返回正确的值。Rails没有抛出批量赋值错误。但是,当我尝试以管理员身份登录并更新用户的管理员状态时,Rails会执行更新操作,并静默忽略admin属性。在Rails控制台中查看用户记录显示记录未被修改。
我感觉这可能是一个我不知道的Ruby或Rails特定问题。我找不到有关使角色动态的任何信息。我能找到的最好的是这个

2
如果我理解正确的话,你已经回答了自己的问题。如果是这样,你应该将你的答案发布为一个答案(而不是编辑你的问题),并接受它。 - David J.
2个回答

3

我这个模型中留下了一个错误的attr_accessor :admin,这是之前试图让它起作用时留下的。我忽略了它。去掉它就解决了问题。

所以,要点就是在Rails 3.2中实现动态角色的方法非常简单。


0

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