2012-09-13 35 views
1

創建一個對象的實例是否有在AR關係,那將是:dependent => destroy相反創建的對象的DSL(即創建一個對象,以便它始終存在)。說,例如,我有以下幾點:如何在默認情況下在HAS_ONE關係

class Item < ActiveRecord::Base 
    #price 
    has_one :price, :as => :pricable, :dependent => :destroy 
    accepts_nested_attributes_for :price 
    .... 

class Price < ActiveRecord::Base 
    belongs_to :pricable, :polymorphic => true 
    attr_accessible :price, :price_comment 

我想我想的要創建的代價,即使我們沒有指定價格每一次?是唯一的(或最好的)選項來做這個回調,還是有辦法通過DSL來做到這一點(類似於:denpendent => :destroy)?

+0

沒有價格/ price_comment創建的對象? – meagar

+0

見下文,是否沒有價格是免費的? – timpone

+0

那有什麼區別?如果您使用'null'或'0.00'價格創建'Price'對象,而不是創建價格對象?如果您*需要*價格,則應強制用戶輸入價格或明確選擇「免費」。 – meagar

回答

0

沒有,因爲幾乎沒有用例此。如果記錄不能沒有相關的記錄存在,則可能應該防止記錄被保存,不裏上演某種僞空對象來代替它。

的最接近將是一個before_save回調:

class Item < ActiveRecord::Base 
    has_one :price, :as => :pricable, :dependent => :destroy 
    accepts_nested_attributes_for :price 

    before_save :create_default_price 

    def create_default_price 
    self.price ||= create_price 
    end 

end 
0

您應該只運行這段代碼上創建一個時間和使用的便捷方法create_price這裏:爲什麼你會想要一個價格

class Item < ActiveRecord::Base 
    has_one :price, :as => :pricable, :dependent => :destroy 

    accepts_nested_attributes_for :price 

    after_validation :create_default_price, :on => :create 

    def create_default_price 
    self.create_price 
    end 
end 
+0

pricable確實看起來很時髦(雖然價格不太好看 - 但肯定是正確的)。謝謝。 – timpone