验证失败时丢失的 Rail accepts_nested_attributes >构建



当使用位置模型的accepts_nested_attributes保存到location模型时发生验证时,Rails将在表单之前包含值时返回空白。

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

当没有发生验证错误时,它会创建完全正确的位置,但是当表单的任何部分发生验证错误,位置字段的数据似乎丢失了。

有什么想法吗?

控制器代码

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

这是一个类似于这里的问题:rails fields_for在嵌套表单上出现验证错误后不会呈现

看看第一个答案,这应该有助于

最新更新