simple but effective usecase – attr_accessible in rails 3.1

We have the following situation:

A rails 3.1 – project we are working on

We have a model called recipe, we want to allow access for mass assignment for a limited set of attributes for “normal users”, and for all attributes for the users with the “admin” role.

This can be done as follows:

class Recipe < ActiveRecord::Base attr_accessible :attr1, :attr2, :attr3 attr_accessible :attr1, :attr2, :attr3, :attr4, :attr5, :as => :admin
.....

This way attr4 and attr 5 will be accessible using mass-assignment only by the admin role….

But in our case we want ALL attributes to be accessible to the admin role, we do not want to write a long and complete list of all attributes. This would save us a lot of work in case we decide to create new attributes using migrations for example.

So we found out we can use the method attribute_names and the splat operator(*) to dynamically create a list of all attribute of that class which can be passed as parameters to the attr_accessible call.

class Recipe < ActiveRecord::Base attr_accessible :attr1, :attr2, :attr3 attr_accessible *attribute_names, :as => :admin
.....

And it works just fine 🙂

Note: if you want to include also all has_many, has_one, has_and_belongs_to_many relations/associations you can use something like this

attr_accessible *(attribute_names + reflect_on_all_associations.collect(&:name)), :as => :admin

Leave a Reply

Your email address will not be published. Required fields are marked *