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

折月煮酒 提交于 2019-12-05 17:48:40

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.

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

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

params.require(:book).permit(:title, :description, { style: [:font, :color] })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!