Elliot
Elliot

Reputation: 2289

Rails accepts_nested_attributes > build being lost on validation fail

When a validation occurs whilst saving to the location model using accepts_nested_attributes for the location model, Rails will return the form blank when it previously held values.

class Sale < ActiveRecord::Base
  belongs_to :location
  belongs_to :user
end

class Location < ActiveRecord::Base
  belongs_to :user
  has_many :sales
  validates_presence_of :street_address, :town, :state, :zip
end

class User < ActiveRecord::Base
  has_many :sales
  has_many :locations
end

When no validation error occurs, it will create the location absolutely fine, however when a validation error occurs on any part of the form, it seems the location fields' data is lost.

Any ideas?

Controller code

def new
    user = User.find(current_user.id)
    1.times { @sale.items.build; @sale.build_location; @sale.sale_times.build; }
  end

  def create
    @sale = Sale.new(params[:sale])
    respond_to do |format|
      if @sale.save
        format.html { redirect_to @sale, notice: 'Sale was successfully created.' }
        format.json { render json: @sale, status: :created, location: @sale }
      else
        format.html { 
          1.times { @sale.items.build; @sale.build_location;  }
          render action: "new" 
          }
        format.json { render json: @sale.errors, status: :unprocessable_entity }
      end
    end
  end

Upvotes: 1

Views: 1376

Answers (1)

Norto23
Norto23

Reputation: 2269

This is a similar question to the one here: rails fields_for does not render after validation error on nested form

Look at the first answer and that should help

Upvotes: 2

Related Questions