【发布时间】:2012-04-02 05:45:08
【问题描述】:
如果在使用位置模型使用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
【问题讨论】:
-
遇到完全相同的问题... :(
-
贴控制器代码就很容易解决了。
-
@soundar 用控制器代码更新了我的帖子
-
@Elliot 您已使用 build_location 但您尚未在 Sale 模型中声明 has_one :location
-
你有
form.fields_for :items, @sale.items.first do |item_fields|...吗?
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord activemodel