Rails:嵌套属性参数中的数组列参数数量错误(给定 0,预期 1..2)

Rails: array column inside nested attribute params wrong number of arguments (given 0, expected 1..2)

我不知道它是否相关,但我正在使用 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: []
  ]
)

这个语法看起来有点像黑魔法,但实际上它很普通 ruby:

irb(main):001:0> [:foo, :bar, baz: 1]
=> [:foo, :bar, {:baz=>1}]

Why does :unit_type[] cause "wrong number of arguments (given 0, expected 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 已经将任何以括号结尾的参数扩展为数组和散列。