簡體   English   中英

具有多態性has_many協會的工廠女孩

[英]Factory Girl with polymorphic has_many association

我正在嘗試使用新語法與多態關聯建立factorygirl 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

您尚未在工廠內聲明關聯的地址,請嘗試

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

有關如何自定義關聯的更多詳細信息,請參見https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

該要點可能會有所幫助-https: //gist.github.com/travisr/2830535/

class Alert < ActiveRecord::Base
  belongs_to :alertable, :polymorphic => true
end


class Region < ActiveRecord::Base
  has_many :alerts, :as => :alertable
end


FactoryGirl.define do
  Factory.define :alert do |alert|
    alert.alertable { |a| a.association(:region) }
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM