Search code examples
ruby-on-railsrubystrong-parameters

Strong Parameters create with belongs_to


I have a Course model which belongs_to a Grade. I'm trying to create a Course in my seeds.rb file by doing:

Course.create(
  ActionController::Parameters.new(
    grade: Grade.all.sample
  ).permit(:grade_id)
)

This creates a new Course object but grade_id is nil. What am I doing wrong?


Solution

  • Strong parameters does two things: one is the white listing of parameters side of things (so the keys in the hash must match the arguments passed to permit, even if setting grade ends up setting grade_id.

    The second thing it does is restrict the types of parameters that are passed - a lot of the recent security problems have occurred when an attacker is able to set a parameter to a carefully constructed hash/array/etc when you were only expecting a string or a number.

    As a result anything that isn't a scalar value is stripped out, with arrays/hashes only allowed if you've indicated that you're expecting an array/hash. In particular your activerecord objects will be stripped out.

    You could switch to setting grade_id instead it just not use strong parameters here - there's no untrusted user input in this case.