当使用location
为位置模型保存到accepts_nested_attributes
模型时进行验证时,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
答案 0 :(得分:1)
这与此处的问题类似:rails fields_for does not render after validation error on nested form
查看第一个答案,这应该有帮助