8

我有一个带有包含admin属性的用户模型的 Rails 应用程序。它被锁定使用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.active_record.whitelist_attributes = true入了config/application.rb

我已经验证该current_user_role方法是否根据当前用户的管理员状态返回正确的值。Rails 不会抛出质量分配错误。但是,当我以管理员身份登录时尝试更新用户的管理员状态时,Rails 会执行更新并默默地忽略该admin属性。在 Rails 控制台中拉出用户的记录表明该记录尚未被修改。

我感觉有一个我不知道的特定于 Ruby 或 Rails 的问题在起作用。我找不到有关使角色动态化的任何信息。我能找到的最好的就是这个

4

2 回答 2

3

我的模型中有一个错误的 attr_accessor :admin 是之前尝试让它工作的结果。我忽略了它。删除它修复它。

因此,结果是,这是一种让动态角色在 Rails 3.2 中工作的非常简单的方法。

于 2012-07-23T16:58:36.480 回答
0

看起来这可能是 Rails 3.2 中的错误

https://github.com/stffn/declarative_authorization/issues/127

于 2012-03-15T19:53:53.557 回答