2012-02-08 15 views
3

ここに状況があります。ruby​​ on rails、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ですか? –

+0

ありがとうございました[FactoryGirlと多相関連の – efoo

+0

複製可能]を追加しました(http://stackoverflow.com/questions/7747945/factorygirl-and-polymorphic-associations) – Thilo

答えて

3

あなたの二FactoryGirlの試みは近いですが、その構築されたアドレスで何かをする必要があります。

FactoryGirl.define do 

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

end 
+0

素晴らしいです。私はそれが入れ子になっている必要があると信じています。 – efoo

+0

確かに、あなたの住所が持つべき属性をFactory.buildの第2引数として渡すことができます。 –

+0

正解、私はこの特定の例を機能させることを意味しました。 – efoo

関連する問題