Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

Strong Parameters with Nested Objects in Rails 4

As the issue I reported, Strong Parameters being introduced in Rails 4 potentially causes users to be confused. Now that the responsibility to ensure params to be secure is owed by controllers, users have to handle several params which users was probably not conscious before by their own.

Imagine there is a model Author which has many Books and you allow Author object to update/destroy the associated objects:

class Author < ActiveRecord::Base
  has_many :books
  accepts_nested_attributes_for :books, allow_destroy: true
end

If you update/destroy the associated objects through Author's nested attributes, you have to explicitly designate id and _destroy params for permitted keys like below:

def author_params
  params.require(:author).permit(:name, ..., {
    books_attributes: [
        :title,

        # ... snip ...

        :id,       # XXX
        :_destroy  # XXX
      ]
    }
  )
}

I think it's a bit obfuscate and difficult for those who are beginners to Rails or have gotten accustomed to Rails 3's way. To avoid getting stucked into mysterious behaviour, you might want to check it out in advance, before Rails 4 is released.