【问题标题】:rails: how to update multiple records using "accepts_nested_attributes"rails:如何使用“accepts_nested_attributes_for”更新多条记录
【发布时间】:2017-04-14 20:18:25
【问题描述】:

假设我有一个 cat 模型和一个 life 模型。假设一只猫 (@cat) has_many 生活,一只猫 accepts_nested_attributes for 生活。 现在,如果我想一次更新 7 个生命 (@lives),使用一个 form_for(@cat),该表单会是什么样子?这是我尝试过的,但在这种形式下,只有上一世的属性被传递给 params 哈希:

  <%= form_for(@cat) do |f| %>
    <% @lives.each do |life| %>
      <%= f.fields_for(life) do |l| %>
        <%= l.input :date_of_birth, as: :date %>
      <% end %>
    <% end %>
    <%= f.submit %>
  <% end %>

【问题讨论】:

    标签: ruby-on-rails simple-form nested-forms nested-attributes


    【解决方案1】:

    您需要在控制器中构建属性

    @cat = Cat.find(<criteria>)
    @cat.lives.build
    

    在您的示例中,循环中有一个循环。试试这个:

    <%= form_for(@cat) do |f| %>
      <%= f.fields_for(:lives) do |l| %>
        <%= l.input :date_of_birth, as: :date %>
      <% end %>
      <%= f.submit %>
    <% end %>
    

    【讨论】:

    • 不行;我的问题不是控制器操作,而是如何将所有 7 个生命的输入“date_of_birth”传递到参数哈希中。所以我想看看 params 哈希像:
    • "cat"=>{"lives"=>{ {"life01"=>{"date_of_birth"=>"01-01-1950"}}, {"life02"=>{" date_of_birth"=>"01-01-1951"}} 等 }
    • 然后,在 (cat-) 控制器中,循环遍历 params[:cat][:lives],并更新生命值。
    • 上面的代码应该做到这一点。我给出的代码中的 params 哈希是什么样的?
    • 只有一个人的生活/date_of_birth: "cat"=&gt;{"lives"=&gt;{"date_of_birth"=&gt;"01-01-1950"}}
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多