1

我正在尝试使用新语法建立一个带有多态关联的 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
4

2 回答 2

2

您还没有在工厂内声明地址的关联,请尝试

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

于 2013-05-01T05:30:06.347 回答
-1

This gist may help - 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
于 2013-08-07T13:50:57.690 回答