Rails 3.1 attr_accessible validation gets an array of roles

I would like to use the new dynamic function attr_accessible. However, each of my users has many roles (I use declarative authorization). Therefore, in my model there is the following:

class Student < ActiveRecord::Base attr_accessible :first_name, :as=> :admin end 

and I pass this in my controller:

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

user_roles is an array of characters:

  user_roles = [:admin, :employee] 

I would like my model to check if one of the characters in the array matches the declared attr_accessible. Therefore, I avoid duplication.

For example, given that user_roles = [: admin ,: employee]. It works:

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

but it is useless if I can only check one role or character, because all my users have many roles.

Any help would be greatly appreciated.

*************** UPDATE ***

You can download the sample application here: https://github.com/jalagrange/roles_test_app

There are 2 examples in this application: students in which y cannot update any attributes, despite the fact that "user_roles = [: admin ,: student]"; And people in which I can only change the first name, because I use "user_roles.first" in the controller update action. Hope this helps. I am sure someone else should have this problem.

+4
source share
1 answer

You can defuse the ActiveModel bulk module as follows:

 # 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 

This way you can pass the array as a parameter :as to update_attributes

Note that this is probably interrupted if accessible_attrs_configs contains a BlackList (using attr_protected )

+1
source

All Articles