2012-02-08 89 views
3

這就是情況。軌道上的紅寶石,factory_girl,validates_presence_of和多態關聯

寶石:導軌3.2,factory_girl 2.5.1

class House 
    has_one :address, :as => :addressable 
    validates :address, :presence => true 
    accepts_nested_attributes_for :address 
end 

class Address 
    attr_accessor :nested 
    belongs_to :addressable, :polymorhic => true 
    validates :addressable, :presence => true, :unless => :nested 
end 

該如何工作。

<%= form_for @house do |f| %> 
    <%= f.label :name %> 
    <%= f.text_field :name %> 
    <%= f.fields_for :address do |a| %> 
    <%= a.hidden_field :nested %> 
    <%= a.label :street_address %> 
    <%= a.text_field :street_address %> 

什麼是定義工廠的正確方法?

# does not work 
Factory.define :house do |h| 
    h.association :address 
end 

# does not work 
Factory.define :house do |h| 
    h.after_build do |record| 
    Factory.build(:address, :addressable => record, :nested => '') 
end 
end 

# does not work 
Factory.define :house do |h| 
    h.after_build do |record| 
    Factory.create(:address, :addressable => record, :nested => '') 
    end 
end 

因此,基本上,「特技」,讓accepts_nested_attributes_for:地址繞過驗證和建立在同一時間都記錄不factory_girl工作。目前,這個醜陋的混亂是唯一的解決方案。

home = House.new 
home.name = 'On the prairie' 
home.address_attributes = Factory.attributes_for(:address, :nested => '') 
home.save 

UPDATE 解決方案:

Factory.define :house do |h| 
    h.after_build do |record| 
    record.address = Factory.build(:address, :addressable => record) 
    end 
end 
+0

您使用的是什麼版本的FactoryGirl?這是Rails3嗎? – 2012-02-08 05:23:59

+0

謝謝,添加它們 – efoo 2012-02-08 05:33:28

+0

[FactoryGirl和多態關聯]的可能重複(http://stackoverflow.com/questions/7747945/factorygirl-and-polymorphic-associations) – Thilo 2012-10-22 10:51:48

回答

3

你的第二個FactoryGirl嘗試接近,但你需要做的與內置的地址什麼的。

FactoryGirl.define do 

    factory :house do 
    after_build do |house| 
     house.address = Factory.build(:address) 
    end 
    end 

end 
+0

太棒了。我相信它需要嵌套。 – efoo 2012-02-08 05:53:33

+0

當然,您可以將您想要的地址的任何屬性作爲Factory.build的第二個參數傳遞。 – 2012-02-08 06:04:01

+0

正確,我只是想讓這個特定的例子工作。 – efoo 2012-02-08 14:11:51