2013-05-01 82 views
1

我想設置一個工廠女孩has_many協會與polmorphic協會,使用新的語法。這是代碼。它沒有正確地建立地址,並將其與網站相關聯。工廠女孩與多態has_many協會

class Address < ActiveRecord::Base 

    belongs_to :addressee, :polymorphic => true 

end 

class Site < ActiveRecord::Base 

    has_many addresses, :as => :addressee, :dependent => :destroy 

end 

***** FACTORYGIRL ****** 


FactoryGirl.define do 
    factory :address, class: 'Address' do 
     property_type "House" 
     street_number "31" 
     street_type "STREET" 
     suburb "XXXXX" 
     postcode "XXXX" 
    end 

    factory :site_address, class: 'Address' do 
     property_type "House" 
     street_number "31" 
     street_type "STREET" 
     suburb "XXXX" 
     postcode "XXXX" 
     site 
    end 
end 


FactoryGirl.define do 

    factory :site, class: 'Site' do 
     name "MyString" 
     organisation_category nil 
     service_type_organisation_category_id 1 
     telephone "MyString" 
     fax "MyString" 
     email "MyString" 
     url "MyString" 
     clinical_software_package_id 1 
     billing_software_package_id 1 
     bulk_billing false 
     disabled_access false 
     ncacch false 
     parking false 
     organisation nil 

     factory :site_with_addresses do 
      ignore do 
       address_count 1 
      end 

      after (:create) do |site,evaluator| 
       FactoryGirl.create_list(:site_address, evaluator.address_count, addressee: site) 
      end 
     end 

    end 


end 

回答

2

您還沒有宣佈工廠地址內的協會,嘗試

factory :address, class: 'Address' do 
    property_type "House" 
    street_number "31" 
    street_type "STREET" 
    suburb "XXXXX" 
    postcode "XXXX" 
    association :addressee, :factory => :site 
end 

有關如何自定義協會

+1

我想這是行不通的。因爲他沒有工廠叫'收件人'。 '如果工廠名稱與協會名稱相同' – ck3g 2013-05-01 05:48:02

+0

嘿傢伙, https://gist.github.com/emilevictor/a376231cf11345b35e1b 這裏是我的網站工廠的工廠女源。我認爲我已經包含了它,但我不小心將地址工廠包含在內。相關的代碼是:site_address和:site。 我正在使用的當前方法(如網站所示)是錯誤的。 – 2013-05-01 05:51:52

+0

這對我來說非常合適。 FactoryGirl似乎明白':addressee'是一個多態關聯,它正確設置Address對象的':addressee_id'和':addressee_type'屬性。 – Franco 2014-04-27 19:04:21