简体   繁体   English

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

[英]Rails 4 nested attributes multiple records when updating

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. 当我更新产品rails时,正确更新产品属性,但是正在创建另一个标记记录,而不仅仅是更新它。

here is my code : 这是我的代码:

View form: 查看表格:

 <%= 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 %>

product model : 产品型号:

 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

tags model : 标签型号:

 class Tag < ActiveRecord::Base
        belongs_to :product, :foreign_key => "product_id"
        # before_save { name.downcase! }

    end

product controller: 产品控制器:

 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

Many thanks 非常感谢

You have to pass the tag id in the permit params in your controller 您必须在控制器中的许可参数中传递标记ID

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM