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

3

8

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.

Baccate answered 13/8, 2010 at 10:22 Comment(0)
B
6

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
Baccate answered 12/11, 2011 at 21:15 Comment(0)
T
2

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).

Tellurize answered 16/1, 2011 at 4:41 Comment(1)
monkeypatching no longer needed, yay! config.active_record.mass_assignment_sanitizer = :strictBaccate
D
0

I am not sure if this would work, but you could write a test to see if your object "respond_to(:unexpected_attr)". You can then tried to force feed it that attr

Alex

Diep answered 13/1, 2011 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.