簡體   English   中英

Rails:嵌套屬性參數內的數組列錯誤的 arguments 數量(給定 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參數上添加[]時會發生這種情況(見上文)。

如果我將其刪除,則表單會提交,但不會保存該列。

我想重申所有其他字段都正確保存。 只有這個數組列完全忽略它。

如果您需要應用程序其他部分的更多信息或更多代碼,請在評論中告訴我。

要將要傳遞帶有空數組的 hash 鍵的標量值數組列入白名單:

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}]

為什么:unit_type[]會導致“arguments 的數量錯誤(給定 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 已經將任何以括號結尾的參數擴展為 arrays 和哈希。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM