Rails 4嵌套在更新时属性多个记录

我被卡住了,我不知道为什么它不能正常工作。 我有一个有许多标签的模型产品。 当我更新产品rails时,正确更新产品属性,但是正在创建另一个标记记录,而不仅仅是更新它。

这是我的代码:

查看表格:

  


产品型号:

  class Product  "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  "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

 def product_params params.require(:product).permit(:name, :description, tags_attributes: [:id,:name]) end 
Interesting Posts