Editing Triple Nested Fields is Creating Duplicates Rails 5.1

43 views Asked by At

I have a triple nested resource, which I am able to create new values for perfectly well. However when trying to edit the record, I am getting duplicated fields for the nested values, which is then creating multiple entries.

I am multiplying the nested fields by 3.

  def new
    @roast = Roast.new
    3.times {@roast.countries.build.regions.build}
  end

Edit method:

  def edit
    @roast = Roast.friendly.find(params[:id])
    3.times {@roast.countries.build.regions.build}
  end

Should I be removing the 'build' element here? I do want the user to be able to add new values if required however.

And create has nothing special for this:

  def create
    @roast = Roast.new(roast_params)

    respond_to do |format|
      if @roast.save
        format.html { redirect_to @roast, notice: 'Roast was successfully created.' }
        format.json { render :show, status: :created, location: @roast }
      else
        format.html { render :new }
        format.json { render json: @roast.errors, status: :unprocessable_entity }
      end
    end
  end

I obviously want the 3 nested fields to show on the edit page, but what am I doing wrong for it to keep repeating.

1

There are 1 answers

1
Pablo On BEST ANSWER

You don't need to add countries or regions in the edit. Just find the Roast.

#This is wrong
3.times {@roast.countries.build.regions.build}

When you edit a Roast, you can access its countries through @roast.countries If you want, you can define an instance variable to use in the form (although not needed) @countries = @roast.countries