简体   繁体   English

具有多态性has_many协会的工厂女孩

[英]Factory Girl with polymorphic has_many association

I'm trying to set up a factorygirl has_many association with a polmorphic association, using the new syntax. 我正在尝试使用新语法与多态关联建立factorygirl has_many关联。 Here is the code. 这是代码。 It isn't properly building the address, and associating it with the site. 它没有正确建立地址,并将其与站点关联。

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

You haven't declared the association within the factory for address, try 您尚未在工厂内声明关联的地址,请尝试

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

See https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations for more details about how to customise your associations 有关如何自定义关联的更多详细信息,请参见https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

This gist may help - https://gist.github.com/travisr/2830535/ 该要点可能会有所帮助-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