我有一个 field 表,我正在 field 编辑页面上使用嵌套表格将报价添加到每个 field 。但是,每次我添加新商品时,fields_for表单都会保存输入的文本,并为要添加的其他商品记录创建新的空白表单。
我只希望一个“添加新报价”表格,而不是每个添加的记录一个。
没有添加优惠-这很好:
添加了一个要约-现在有2个“添加新要约”表格和部分不想要的空白要约:
这是我希望在添加一个报价后的样子:
新的空白要约表格和空白部分的数量随 Controller 中内置的数量而改变(以分钟为单位)。
field 管理员
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
field 模型
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 %>
关于ruby-on-rails - 如何停止与已添加记录重复的fields_for嵌套表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6806030/