Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails and attr_accessible: is there a way to raise an exception if a non-mass-assignable attribute is mass-assigned?

Is there a way to have rails raise an error if an attempt is made to mass-assign attributes that aren't allowed by attr_accessible?

This would be handy in development to remind me why my shiny new model isn't working, and also good to log in production in order to detect malicious activity.

I'm using rails 2.3.8 but will probably soon be migrating to 3.

like image 351
John Bachir Avatar asked Aug 13 '10 10:08

John Bachir


2 Answers

As of Rails 3.2 this no longer requires monkeypatching -- rails provides this behavior now. Put this in development.rb and test.rb:

config.active_record.mass_assignment_sanitizer = :strict
like image 133
John Bachir Avatar answered Oct 08 '22 17:10

John Bachir


I would suggest something like the Bento project has incorporated into their Rails app.

They create a Rails Initializer under config/initializers/ and then override the appropriate method in the ActiveModel class to raise a MassAssignmentError (within non-production environments).

like image 27
Walking Wiki Avatar answered Oct 08 '22 17:10

Walking Wiki