Rails 4嵌套属性更新时有多个记录 [英] Rails 4 nested attributes multiple records when updating
本文介绍了Rails 4嵌套属性更新时有多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被卡住了,我不知道为什么它不能正常工作. 我有一个模型产品,其中有很多标签. 当我更新产品栏时,会正确更新产品属性,但会创建另一个标签记录,而不仅仅是更新它.
I'm stuck and i don't know why it is not working right. I have a model product wich has many tags. When i update the product rails update properly the products attributes but is creating another tag record instead of just updating it.
这是我的代码:
查看表单:
<%= form_for ([@product.user, @product]), id: 'edit_form' do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.fields_for :tags do |t| %>
<%= t.label :name %>
<%= t.text_field :name %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
产品型号:
class Product < ActiveRecord::Base
belongs_to :user, :foreign_key => "user_id"
has_many :tags, :dependent => :destroy
accepts_nested_attributes_for :tags, reject_if: :all_blank, allow_destroy: true, :update_only => true
end
标签模型:
class Tag < ActiveRecord::Base
belongs_to :product, :foreign_key => "product_id"
# before_save { name.downcase! }
end
产品控制器:
def edit
user = User.find(params[:user_id])
@product = user.products.find(params[:id])
@tags = @product.tags.all
respond_to do |format|
format.html
format.js
end
end
def update
user = User.find(params[:user_id])
@product = user.products.find(params[:id])
@tags = @product.tags.all
respond_to do |format|
if @product.update(product_params)
format.html { redirect_to([@product.user, @product], :notice => 'Product successfully updated.') }
else
format.html { render :action => "edit" }
end
end
end
def product_params
params.require(:product).permit(:name, :description, tags_attributes: :name)
end
非常感谢
推荐答案
您必须在控制器的允许参数中传递标签ID
You have to pass the tag id in the permit params in your controller
def product_params
params.require(:product).permit(:name, :description, tags_attributes: [:id,:name])
end
这篇关于Rails 4嵌套属性更新时有多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文