我不知道它是否相关,但是我正在使用Cocoon Gem。
我要保存的主要资源是财产。
我已经将此属性的嵌套属性称为 property_unit_attributes
params.require(:property).permit(
...
property_units_attributes: [:id, :rent, :floor, :suite_number, :square_feet, :unit_type[], :ceiling_height, :condition, :amenities, :_destroy]
);
问题在于unit_type
嵌套表单上的复选框是否接受这些属性
我将不包括整个表单,因为除我的数组外,所有属性均正确保存。这是我下面的一些复选框字段:unit_type
<div class="field">
<%= f.check_box :unit_type, { multiple: true, class: 'field__checkbox' }, 'condominium', nil %>
<label>Condominium</label>
</div>
<div class="field">
<%= f.check_box :unit_type, { multiple: true, class: 'field__checkbox' }, 'general_business', nil %>
<label>General Business</label>
</div>
<div class="field">
<%= f.check_box :unit_type, { multiple: true, class: 'field__checkbox' }, 'health_care', nil %>
<label>Health Care</label>
</div>
<div class="field">
<%= f.check_box :unit_type, { multiple: true, class: 'field__checkbox' }, 'hostpitality_or_hotel', nil %>
<label>Hospitality / Hotel</label>
</div>
以及呈现的HTML的示例:
<div class="field">
<input class="field__checkbox" type="checkbox" value="land" name="property[property_units_attributes][0][unit_type][]" id="property_property_units_attributes_0_unit_type_land">
<label>Land</label>
</div>
当我提交表单时,所有属性都显示在请求中。我将仅介绍以下属性:
"property_units_attributes"=>{"0"=>{"rent"=>"33.0", "floor"=>"33", "suite_number"=>"[FILTERED]", "square_feet"=>"33", "unit_type"=>["condominium", "industrial", "office"], "ceiling_height"=>"33.0", "condition"=>"3", "amenities"=>"3", "id"=>"10"}},
如您所见,我选中了三个复选框,它们被放置在一个数组中:
"unit_type"=>["condominium", "industrial", "office"]
提交时,出现此错误: wrong number of arguments (given 0, expected 1..2)
这发生在我添加[]
对:unit_type
下嵌套属性参数(见上文)。
如果我将其删除,则将提交表单,但不会保存该列。
我想重申所有其他字段正确保存。仅此数组列会完全忽略它。
如果您需要应用程序其他部分的更多信息或更多代码,请在评论中告知我。
要将标量值数组列入白名单,您需要传递带有空数组的哈希键:
params.require(:property).permit(
...
property_units_attributes: [
:id, :rent, :floor, :suite_number,
:square_feet, :unit_type, :ceiling_height,
:condition, :amenities, :_destroy,
unit_type: []
]
)
这个语法看起来像是黑魔法,但实际上只是普通的旧红宝石:
irb(main):001:0> [:foo, :bar, baz: 1]
=> [:foo, :bar, {:baz=>1}]
为什么会
:unit_type[]
导致“参数数量错误(给定0,应为1..2)”?
如果尝试:unit_type[0]
,可以看到它调用了符号上的方括号访问器方法:unit_type
。
irb(main):014:0> :unit_type[0]
=> "u"
irb(main):015:0> :unit_type.method("[]")
=> #<Method: Symbol#[](*)>
如果要声明带有方括号的符号或其他具有特殊意义的字符,Ruby对此有特殊的语法:
:"unit_type[]"
当然,这无法解决问题,因为Rack已经将以方括号结尾的所有参数扩展为数组和哈希。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句