我有一个场地表,我使用场地编辑页面上的嵌套表单向每个场地添加报价。但是,每次我添加新的报价,fields_for表单都会保存输入的文本,并创建一个新的空白表单以添加另一个要约记录。

我只希望每个记录的“添加新报价”表格不是一个。

没有添加优惠 - 这很好: enter image description here

添加了一个报价 - 现在有2个“添加新优惠”表格和不需要的空白优惠部分:

enter image description here

这就是我想要的,在添加一个报价之后的样子: enter image description here

新空白的报价表格和空白部分随着控制器的构建数量而变化(其1时)

场地控制器

class VenuesController < ApplicationController   
  def edit
    @venue = Venue.find(params[:id])
    1.times { @venue.offers.build }
  end

  def update
    @venue = Venue.find(params[:id])
    if @venue.update_attributes(params[:venue])
      flash[:notice] = 'Venue updated successfully'
      redirect_to :back
    end
  end
end

场地模型

class Venue < ActiveRecord::Base
  has_many :offers
  accepts_nested_attributes_for :offers
end

场地edit.html.erb

      <%= form_for @venue do |f| %>

        <h2 class="venue_show_orange">Offers</h2>

        <div class="edit_venue_details">
          <% if @venue.offers.count.zero? %>
            <div class="no_offers">
              No offers added yet.
            </div>
          <% else %>
            <%= render :partial => 'offers/offer', :collection => @venue.offers %>
          <% end %>

          <div class="clearall"></div>

          <h2 class="edit_venue_sub_header">Add a new offer</h2>    

          <%= f.fields_for :offers do |offer| %>
            <p class="edit_venue">title: <br>
            <%= offer.text_field :title, :class => "edit_venue_input" %></p>
          <% end %>
        </div>

        <button class="submit_button" type="submit"> Save changes</button>
      <% end %>

那么,我如何在“场地编辑”页面上只有一个添加新的报价表格,这使我可以添加一个新的报价,然后将其空白以便再次使用呢?另外,是否有任何方法可以防止空白提供部分?

非常感谢您的任何帮助!

有帮助吗?

解决方案

class VenuesController < ApplicationController   
  def edit
    @venue = Venue.find(params[:id])
  end
  ...
end

场地edit.html.erb

<%= f.fields_for :offers, @venue.offers.build do |offer| %>
  <p class="edit_venue">title: <br>
  <%= offer.text_field :title, :class => "edit_venue_input" %></p>
<% end %>

其他提示

我不确定这是否会起作用,但是您是否尝试过以下操作?

<%= f.fields_for @venue.offers.last do |offer| %>

我认为问题是您将其传递给符号:要约,这会导致字段为所有报价创建字段,但是您也应该能够将特定对象传递给fields_for方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top