0

Cannot find anywhere the accepted way to create a model without going through controller considering that attr_accissible is no longer supported.

Is the below approach correct?

in my old code:

ModelName.create(course_id:680, user_id:25)

(raises mass_assignment error now that I have removed attr_accessible)

new code:

model = ModelName.new.tap do |m| 
  m.course_id = 680
  m.user_id = 25
end
model.save!

(works but looks hacky)

Apparently, the below will not work because without_protection option is removed in Rails4

ModelName.create({course_id: 680, user_id: User.first.id}, without_protection: true)

Thanks to this question I've read about strong parameters 'Use outside of Controllers' - link but even if I do the following from my console:

raw_params = {course_id: Course.last.id, user_id: User.first.id}
parameters = ActionController::Parameters.new(raw_params)
ModelName.create(parameters.permit(:course_id, :user_id))

I get error

WARN -- : WARNING: Can't mass-assign protected attributes for ModelName: course_id, user_id
Community
  • 1
  • 1
ryan2johnson9
  • 724
  • 6
  • 21
  • If mass-assignment of attributes is optional for your model you can avoid such situation by changing this line `config.active_record.mass_assignment_sanitizer = :strict` to `config.active_record.mass_assignment_sanitizer = :logger` in your environments/development.rb file – anusha Sep 26 '14 at 03:00

1 Answers1

0

I read this question more carefully and found my answer

I had to add

config.active_record.whitelist_attributes = false

to my environments (development/test/production.rb), maybe because I still have the protected_attributes gem installed.

so now I can happily use

ModelName.create(course_id:680, user_id:25)

afterall.

I realise this question/answer is somewhat of a repeat of the aforementioned question - but I did find that question a bit tricky to understand, so I won't take this question down unless asked.

Community
  • 1
  • 1
ryan2johnson9
  • 724
  • 6
  • 21