ActiveRecord 3.1 - Mass-Assignment Roles

12 May 2011

Rails 3.1 introduces the concept of mass-assignment roles which allow you to specify accessible attributes for a specific permission or role. For instance, if you wanted your users to be able to edit their names, but not their permissions you could limit their accessible attributes but allow administrators to edit permissions:

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :permission, :as => :admin
end

While this syntax is awesome the AR#new, AR#create and AR#update_attributes syntax is horrible:

User.create(params[:user], :as => :admin)

It seems like the same primitive syntax that AR#find used in Rails 2.x:

User.find(:all, :conditions => ['name = ?', params[:name]])

That was replaced with elegant chaining in Rails 3.0:

User.where('name = ?', name).all

Why not do the same with mass-assignment roles?

User.as(:admin).create(params[:user])

or

User.as(:admin).attributes(params[:user]).create

I can see the conflict this might cause with scopes, but maybe there’s an elegant balance so that we aren’t passing multiple hash parameters to AR#new, AR#create and AR#update_attributes.