Whiny protected attributes

Written . Tagged Ruby, Ruby on Rails.

When using attr_accessible/attr_protected to protect attributes during mass-assignment, assignments to protected attributes are silently discarded.

So if you

1
User.create!(:username => "Fool", :age => 12, :admin => true)

and admin is a protected attribute, then the record will still be created but will only assign the username and age.

This can sometimes cause confusion in development, when you accidentally protect an attribute too many, or mass-assign incorrectly. Since the assignments are silently ignored, it can take a while to figure out what’s happening.

Hence this small piece of code.

Stick whiny_protected_attributes.rb (highlighted on Pastie) in the lib directory and then

1
require 'whiny_protected_attributes'

in config/environment.rb.

Once the server has been restarted, ActiveRecord will now throw an exception whenever you try to mass-assign a protected attribute.

In production, an error is logged, but it doesn’t throw, since it makes sense to still ignore it silently to the end-user’s ears.