Reputation: 7956
I have a Timesheet
model without many of its attributes added to attr_accessible
. Trying to create seed data in seeds.rb
but am getting a mass-assign protection error both when running rake db:seed
as well as when trying the code in the console despite using .save(validate: false)
.
Error ouput from rake db:seed
:
rake aborted!
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: spent, worked_time, driving_time
console:
pry(main)> ts = Timesheet.new(spent: 0, review: "none", driving_time: 0, worked_time: 3600).save(validate: false)
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: spent, driving_time, worked_time
from /home/vagrant/.rvm/gems/ruby-1.9.3-p547/gems/activemodel-3.2.18/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
Upvotes: 0
Views: 283
Reputation: 5229
Please, try this:
ts = Timesheet.new({spent: 0, review: "none", driving_time: 0, worked_time: 3600},
without_protection: true).save(validate: false)
more information here
The best practices says that you must white list the fields you want the user update at the model with attr_accessible :spent, :driving_time, :worked_time
if you expect your user send this data with the update or create form.
The option validate: false
prevents the validation before save, but not the mass assignment control.
Upvotes: 1
Reputation: 3597
You need to skip mass-assignment, .save(validate: false)
only skips validations.
Try passing option:
:without_protection => true
what you need to do is:
ts = Timesheet.new(spent: 0, review: "none", driving_time: 0, worked_time: 3600, :without_protection => true).save(validate: false)
Upvotes: 2