2011-10-21 32 views
1

我有機型是這樣的:Rails的模式accepts_nested_attributes_for正常工作

class User < ActiveRecord::Base 
    has_one :business 
end 
class Business < ActiveRecord::Base 
    belongs_to :user 
    has_many : locations 
    accepts_nested_attributes_for :locations, :reject_if => lambda { |a| a[:location].blank?} 
    atr_accessible :name, :locations_attributes 
    ... 
end 

class Location < ActiveRecord::Base 
    belongs_to :business 
    ... 
end 

當我填寫的表格的地址,郵寄形式BusinessesController,日誌顯示的參數是正確的create行動:

... 
"business"=>{"name"=>"sos","locations_attributes"=>{"0"=>{"address"=>"location1"}, "1"=>{"address"=>"location2"}}} 
... 

在BusinessesController

# :Post /usres/1/businesses 
def create 
    @user = User.find(params[:user_id]) 
    @business = @user.build_business(params[:business]) 
    if @business.save 
    ... 
    else 
    ... 
    end 
end 
create動作

我查了一下日誌,發現@business.save沒有在數據庫中插入任何關於locaitons的信息,但只有關於business的信息,但params[:business]明確包含了位置hash,所以我錯了?

+0

爲什麼沒有人幫助我? – Rn2dy

回答

1

我猜它的錯誤在於在reject_if檢查,

accepts_nested_attributes_for :locations, 
    :reject_if => lambda { |a| a[:location].blank?} 

你在哪裏有位置表的位置屬性?據我瞭解,你應該檢查以下方式

accepts_nested_attributes_for :locations, 
    :reject_if => lambda { |a| a[:address].blank?} 
+0

你是對的!謝謝! – Rn2dy