【问题标题】:Rails 3.2, Mass Assignment, Dynamic Roles?Rails 3.2,批量分配,动态角色?
【发布时间】:2012-04-01 08:53:40
【问题描述】:

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

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

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

【问题讨论】:

  • 如果我对您的理解正确,您就回答了自己的问题。如果是这样,您应该将您的答案作为答案发布(而不是对您的问题的编辑)并接受它。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 2013-07-26
      • 2012-08-17
      相关资源
      最近更新 更多