4

When using ActiveRecord, you can configure it to raise an exception on mass assignment in tests by putting this line in config/environments/test.rb:

config.active_record.mass_assignment_sanitizer = :strict

Is there a way to accomplish the same thing with Mongoid?

Luke Francl
  • 31,028
  • 18
  • 69
  • 91
  • Looks like the same question as: [How to protect all fields against mass assignment in mongoid app](http://stackoverflow.com/questions/11205301/how-protect-all-fields-against-mass-assignment-in-mongoid-app). – Stennie Aug 24 '12 at 02:31
  • Not exactly. We have mass assignment disabled, but Mongoid logs instead of raising an exception. In ActiveRecord, this behavior is configurable, and I would like to know if there is a way to turn on exception raising on mass assignment in Mongoid (just for tests). – Luke Francl Aug 24 '12 at 18:51

1 Answers1

4

From reading through the code Mongoid uses ActiveModel for the mass assignment protection. That is exactly the same thing as in Rails but it seems the configuration is not hooked up completely.

From the implementation I could gather this is what happens:

attributes.rb assign_attributes calls into processing.rb.

processing.rb then calls the active_model sanitizer where the call ends up in sanitize. The method that should raise the exception is: process_removed_attributes that gets overridden by the strict sanitizer class or the logging sanitizer.

You now just have to find out how to configure Mongoid to use the strict_sanitizer in this case. I'm investigating further but it seems this is strictly speaking a active_model configuration and has nothing to do with Mongoid.

What works but is not ideal in your case is assigning the mass_assignment_sanitizer on the Model:

Modelname.mass_assignment_sanitizer = :strict

But this will only change it for this one model. I simply can't find any sanitizer references in the mongoid config.

Tigraine
  • 23,358
  • 11
  • 65
  • 110
  • Seems to be fixed in version 4.0, "I'm actually going to move this to 4.0 since Rails mass assignment is changing again in Rails 4, and I actually agree with that change so I'd rather just go straight to that." https://github.com/mongoid/mongoid/issues/2200 – Jonathan Leung Dec 30 '12 at 16:59