-->

How to use Rails Action Controller Nested Params t

2019-05-07 07:05发布

问题:

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.

回答1:

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.



回答2:

It looks like it might need to be:

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

based on this example from the Rails API Guide

   pets: [{
      name: 'Purplish',
      category: 'dogs'
    }]

Edit, I certainly could be wrong, but following the rules quoted here:

TL;DR: Use this rule of thumb when trying to figure out how to whitelist nested attributes: To Permit a Hash, Pass an Array To Permit an Array, Pass a Hash



回答3:

I think it should work if you wrap style in curly braces, i.e.:

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