當使用accepts_nested_attributes
保存到location
模型並保存到location
模型時,Rails將在之前保存值時返回表單空白。Rails accept_nested_attributes>構建在驗證失敗時丟失
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
具有完全相同的問題... :( – RAJ 2012-04-02 05:52:20
如果您發佈控制器代碼,將很容易解決。 – 2012-04-02 06:04:48
@soundar已更新我的帖子,控制器代碼爲 – Elliot 2012-04-02 06:10:47