4

我想使用 rails 新的动态 attr_accessible 功能。但是,我的每个用户都有许多角色(我正在使用声明式授权)。所以我的模型中有以下内容:

class Student < ActiveRecord::Base

attr_accessible :first_name, :as=> :admin

end

我在我的控制器中传递了这个:

@student.update_attributes(params[:student], :as => user_roles)

user_roles 是一个符号数组:

   user_roles = [:admin, :employee]

我希望我的模型检查数组中的一个符号是否与声明的 attr_accessible 匹配。因此,我避免任何重复。

例如,假设 user_roles =[:admin, :employee]。这有效:

@student.update_attributes(params[:student], :as => user_roles.first)

但是如果我只能验证一个角色或符号,因为我的所有用户都有很多角色,那么它是没有用的。

任何帮助将不胜感激

** * ** * ** * ** * ***更新* ** * ** * ** * ** * ** * ** * ** * **

您可以在此处下载示例应用程序: https ://github.com/jalagrange/roles_test_app

此应用程序中有 2 个示例: y 无法更新任何属性的学生,尽管事实上 'user_roles = [:admin, :student]'; 而我只能更改名字的人,因为我在控制器更新操作中使用“user_roles.first”。希望这可以帮助。我确定其他人一定有这个问题。

4

1 回答 1

1

您可以对ActiveModel 的质量分配模块进行猴子修补,如下所示:

# in config/initializers/mass_assignment_security.rb

module ActiveModel::MassAssignmentSecurity::ClassMethods

  def accessible_attributes(roles = :default)
    whitelist = ActiveModel::MassAssignmentSecurity::WhiteList.new
    Array.wrap(roles).inject(whitelist) do |allowed_attrs, role|
      allowed_attrs + accessible_attributes_configs[role].to_a
    end
  end

end

这样,您可以将数组作为:as选项传递给update_attributes

请注意,如果accessible_attrs_configs包含BlackList(来自 using attr_protected) ,这可能会中断

于 2011-09-25T02:25:29.797 回答