Nested Attributes Duplication

40 views
Skip to first unread message

Emmanuel Mathews

unread,
Jul 17, 2013, 6:08:42 AM7/17/13
to compos...@googlegroups.com
I have a duplication problem when using the accepts nested attributes method. I have an app thats an ecommerce app, when I create a new product and add a nested attribute everything works fine. But if I hit edit product and then update changes it creates a duplicate of the nested attributes I had on there before, and it keeps doing it each time I update, even when no changes are made. Is there something Im missing? or is it related to rails 4

This is my model, controller for the following


Product Model

class Product < ActiveRecord::Base
has_many :variants
accepts_nested_attributes_for :variants
end

Variant Model

class Variant < ActiveRecord::Base
belongs_to :product
end

Product Controller

def new
    @product = Product.new
    3.times { @product.variants.build }
end

def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_product
      @product = Product.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def product_params
      params.require(:product).permit(:name, :description, :brand_id, :category_id, :subcategory_id, :slug, variants_attributes: [:sku, :color, :size, :price, :stock, :slug ] )
    end
end

Reply all
Reply to author
Forward
0 new messages