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

时间:2012-03-15 19:21:25

标签: ruby-on-rails ruby mass-assignment attr-accessible

我有一个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.active_record.whitelist_attributes = true中设置了config/application.rb

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

我感觉有一个特定于Ruby或Rails的问题,我不知道。我无法找到有关使角色动态化的任何信息。我能找到的最好的是this

2 个答案:

答案 0 :(得分:3)

我的模型中存在一个错误的attr_accessor:admin,这是因为之前尝试使其工作而留下的。我忽略了它。删除它修复它。

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

答案 1 :(得分:0)

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

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