Mass Assignment in ActiveRecord

Mon May 25 00:00:00 -0700 2009

New plugin! From the README:

What It Is

A robust mass assignment method with a small and obvious syntax.

The normal mass assignment protection comes from attr_protected and attr_accessible. There are a many problems with this approach:

  • Often never implemented, leaving a wide-open system. And once implemented, easy to forget when adding new attributes, leading to bugs (in an attr_accessible system) or security holes (in an attr_protected system).
  • Restricts coding syntax. You can’t easily use update_attributes() or attributes= because your whitelist/blacklist gets in your own way.
  • Not contextual. The list of allowed attributes can’t change to accomodate different user permissions or situations.

This plugin’s solution is to let you specify an obvious list of allowed attributes when you mass assign attributes.

  • The list of allowed attributes is in your controller at calltime, so it’s easier to remember and update (it’s not a hidden, magical system).
  • The list of allowed attributes is optional, so it doesn’t get in your way.
  • Your controller can easily enforce permissions by evaluating the current user (Admin Controller) or the current situation (creates vs updates).

Example

Let’s take a very plausible situation where you would want three separate lists of allowed attributes. You have users that sign up to your application. But after they have signed up, they may not change their username. Admins, however, may manually change a username as needed.

class UsersController < ApplicationController
  def create
    @user = User.new
    # during signup a user may pick a username
    @user.assign(params[:user], [:username, :email, :password, :password_confirmation])
    @user.save!
    ...
  end

  def update
    @user = User.find(params[:id])
    # username is no longer accepted later
    @user.assign(params[:user], [:email, :password, :password_confirmation])
    @user.save!
    ...
  end
end

class Admin::UsersController < ApplicationController
  before_filter :admin_required

  def update
    @user = User.find(params[:id])
    # admins, on the other hand, may change the username as needed, but may not set passwords
    @user.assign(:params[:user], [:username, :email])
    @user.save!
    ...
  end
end

Get it here: http://github.com/cainlevy/mass_assignment/tree/master