How To Bypass Rails Forbidden Attributes Or Mass Assignment Protection For One Time

Posted by Weston Ganger

Sometimes you need to set something that normally would be protected in by forbidden attributes or mass assignment possibly for seeding data or imports. These techniques will work with most ActiveRecord methods including new, create, assign_attributes, update_attributes.


Rails 5

Just call .to_unsafe_hash on your params before passing them in.


User.create(params[:user].to_unsafe_hash)


Rails 4

Just call .to_hash on your params before passing them in.


User.create(params[:user].to_hash)


Rails 3

Just use the without_protection option.


User.create(params[:user], without_protection: true)
# or
User.create({name: 'Weston Ganger', company: 'Solid Foundation Web Development'}, without_protection: true)


Related External Links:

Article Topic:Software Development - Rails

Date:February 09, 2016

Recommended Posts