如何使用Rails操作控制器嵌套参数来允许特定属性散列 [英] How to use Rails Action Controller Nested Params to Permit a Specific Attributes Hash
问题描述
关于嵌套参数有很多问题,但我似乎找不到解决特定情况的简单情况。
我试图允许不是数组的嵌套散列。我预计这会起作用:
params.require(:book).permit(:title,:description,style:{:字体,:color})
但它导致语法错误。 b
然而,这是工作:
params.require(:book).permit(:title ,::description,style:[:font,:color])
它似乎允许 style
值是属性为font和:color的项目数组。我只想允许使用这两个属性的单个散列。
我尝试了其他变体,但是我一直在收到语法错误。
上下文:Rails 4.1.7,Ruby 2.0.0(它在我的待办事项列表中升级!),不使用ActiveRecord。
问题在于,如您的错误状态,您有语法错误。这是因为 {:font,:color}
不是有效的Ruby。您试图将哈希语法 {key:value}
与数组语法混合使用, [:one,:two]
。你可能想要做的是,
#接受参数:{book:{style:{font:value,color :value}}}
params.require(:book).permit(style:[:font,:color])
或
#接受参数:{book:{style:[{font:value, color:value}]}}
params.require(:book).permit(style:[[:font,:color]])
事实上,你使用的是一个键数组接受一个散列(而不是一个数组)是 strong_parameters
的工作原理。要接受一个数组,你实际上只需要做这样的事情,
#Accept params:{book:{style:[: font:color]}}
params.require(:book).permit(style:[])
希望能够澄清问题。
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.
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.
这篇关于如何使用Rails操作控制器嵌套参数来允许特定属性散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!