How to use Rails Action Controller Nested Params to Permit a Specific Attributes Hash

readyornot picture readyornot · Apr 17, 2015 · Viewed 7.7k times · Source

There are a lot of questions about Nested Parameters, but I can't seem to find one that addresses my specific, simple situation.

I'm trying to permit a nested hash that is NOT an array. I expected this to work:

params.require(:book).permit(:title, :description, style: {:font, :color})

But it resulted in a syntax error.

This, however, worked:

params.require(:book).permit(:title, :description, style: [:font, :color])

But my issue with this, it it seems to permit style values that are arrays of items with attributes :font and :color. I only want to permit a single hash with those 2 attributes.

I've tried other variations, but I keep getting syntax errors. I'd appreciate any help with this.

Context: Rails 4.1.7, Ruby 2.0.0 (It's on my todo list to upgrade!), not using ActiveRecord.

Answer

ezekg picture ezekg · Aug 23, 2016

The problem is that, as your error states, you have a syntax error. This is because {:font, :color} is not valid Ruby. You're attempting to mix the hash syntax, { key: value }, with the array syntax, [:one, :two]. What you're likely wanting to do is,

# Accept params: { book: { style: { font: value, color: value } } }
params.require(:book).permit(style: [:font, :color])

or,

# Accept params: { book: { style: [{ font: value, color: value }] } }
params.require(:book).permit(style: [[:font, :color]])

The fact that you're using an array of keys to accept a hash (not an array) is just how strong_parameters works. To accept an array, you would actually just do something like this,

# Accept params: { book: { style: [:font, :color] } }
params.require(:book).permit(style: [])

Hopefully that clarifies the issue.