循环中的嵌套表单

时间:2015-07-31 01:36:54

标签: ruby-on-rails-4 nested-forms

我有一个Inquiry,其中有许多InquiryItem模型,其中有许多InquiryItemPrice

在我的展示视图中,我循环浏览了我的inquiry_items,对于每一个,我需要输入inquiry_item_price的字段。

这些是我的模特:

询问

class Inquiry < ActiveRecord::Base
  belongs_to :company
  has_many :inquiry_items

  accepts_nested_attributes_for :inquiry_items, allow_destroy: true, reject_if: lambda { |a| a[:item_id].blank? && a[:quantity].blank? }
end

InquiryItem

class InquiryItem < ActiveRecord::Base
  belongs_to :inquiry
  belongs_to :item
  has_many :inquiry_item_prices

  accepts_nested_attributes_for :inquiry_item_prices, allow_destroy: true, reject_if: lambda { |a| a[:item_id].blank? && a[:quantity].blank? }
end

InquiryItemPrices

class InquiryItemPrices < ActiveRecord::Base
  belongs_to :inquiry_items
end

InquiriesController

  def show
    @request = Inquiry.find(params[:id])
    @request.inquiry_items.each { |item| item.inquiry_item_prices.build}
  end

show.html.slim

    -@inquiry.inquiry_items.each do |inquiry_item|
      tr
        td =inquiry_item.item.name
        td =inquiry_item.quantity
        =f.fields_for :inquiry_item_prices do |builder|
          td =builder.text_field :price, class:"form-control", placeholder:"Preço"

使用此代码,我加载price的输入,如下所示:

<input class="form-control" placeholder="Preço" type="text" name="inquiry[inquiry_item_prices][price]" id="inquiry_inquiry_item_prices_price">

问题是它不是一个列表所以我只得到最后一个字段值,它应该是这样的:

<input class="form-control" placeholder="Preço" type="text" name="inquiry[inquiry_item_prices][0][price]" id="inquiry_inquiry_item_prices_0_price">

如何正确加载InquiryItemPrice并生成这些输入字段?

1 个答案:

答案 0 :(得分:0)

The solution is just an update on my show.html.slim form tag file

=form_for(@inquiry, url: inquiry_add_prices_path(@inquiry)) do |f|
      table class="table table-striped"
        thead
          tr
            th Nome
            th Quantidade
            th Valor
        tbody
          =f.fields_for :inquiry_items do |item_form|
            tr
              td =item_form.object.item.name
              td =item_form.object.quantity
              =item_form.fields_for :inquiry_item_prices do |price_form|
                td =price_form.text_field :price, class:"form-control", placeholder:"Preço"

          =f.submit "Enviar preços", class: "btn btn-success"

With that it is not required to loop through the @inquiry.inquiry_items since they are being built in the controller show method.