Skip to content

attr_accessible with many roles

October 20, 2012

I recently ran into an interesting issue with attr_accessible due to overlooking certain configurations I made in my application.

The symptom was that when I would add attr_accessible to one of my models, suddenly all of the attributes would be inaccessible.

The problem stems from the fact that I had configured mass_assignment_role (used by attr_accessible) to resolve to :admin automatically if I was logged in as an administrator.

class ActiveRecord::Base
  def mass_assignment_role
    role = mass_assignment_options[:as] || (Authorization.current_user.role_symbols.include?(:admin) ? :admin : :default)
  end
end

The problem is that by defining attr_accessible for the :default role it automatically locks down all attributes for any other role.

The solution was to simple remember to define the accessibility for both roles whenever defining attr_accessible:

class MyModel < ActiveRecord::Base
  @@accessible_attributes = %(attr1 attr2 attr3)
  attr_accessible *@@accessible_attributes
  attr_accessible *@@accessible_attributes, as: :admin
end
Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: