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



我有一个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特定的问题在起作用,我不知道。我找不到任何关于使角色动态化的信息。我能找到的最好的就是这个。

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

因此,结果是,这是一种非常简单的方法,可以让动态角色在Rails3.2中工作。

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

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

最新更新