Mass Assignment Security with Mongoid

July 16, 2012 at 1:06 pm

EDIT – THIS POST WAS RETARDED, AND COMBINED TWO MUTUALLY EXCLUSIVE WAYS OF DEALING WITH THINGS.

You only ever need one OR the other of these approaches – Strong Parameters does not work WITH attr_accessible – if you want to use it, you need to remove the mod below for attr_accessible by default, just like you set whitelist_attributes to false with ActiveRecord.

This is a follow up to this post, which dealt with Mass Assignment Security in ActiveRecord.

Mongoid doesn’t support setting config.active_record.whitelist_attributes = true to enable Mass Assignment Security, so we need a way around this. Essentially, all this switch does is add attr_accessible nil to your models, making you declare each field that you wish to be eligible for Mass Assignment. We can do this very simply with Mongoid by adding an Initializer.

That’s all you need to do – remove the line config.active_record.whitelist_attributes = true altogether from your application.rb, and you are good to go.