Rails 4 nested attributes multiple records when updating

吃可爱长大的小学妹 提交于 2019-12-06 05:09:31

问题


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.

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


回答1:


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


来源:https://stackoverflow.com/questions/17565296/rails-4-nested-attributes-multiple-records-when-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!