我有一个 rails 4 应用程序,它有一个添加页面和一个编辑页面。您可以轻松添加元素(没有问题),但是当您去编辑这些元素并单击保存时,它会再次添加您最初添加的字段。
这是我的_form.html.erb
<%= nested_form_for @store do |f| %>
<%= f.fields_for :products do |product_form| %>
<div class='field'>
<%= product_form.text_field :name %>
<%= product_form.hidden_field :_destroy %>
<%= link_to "REMOVE PRODUCT", '#', class: "remove_fields" %>
</div>
<% end %>
<p><%= f.link_to_add "Add PRODUCT", :products %></p>
<%= f.submit 'Save', :class => "primary small" %>
<% end %>
和我的商店.rb模型:
class Store < ActiveRecord::Base
has_many :products, class_name: "StoreProduct"
accepts_nested_attributes_for :products, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end
我在控制器中的更新操作如下所示:
def update
respond_to do |format|
if @store.update(store_params)
format.html { redirect_to store_products_path(@store), notice: 'Store was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @store.errors, status: :unprocessable_entity }
end
end
end
store_params
在你的控制器中是什么样子的? 如果 id
不是允许的值之一,则可以开始看到每次发生update
操作时创建为新记录的嵌套模型。 您可能希望具有以下内容:
params.require(:store).permit(products_attributes: [:id, :name, :_destroy])
请参阅有关nested_form
gem 强参数的文档。