繁体   English   中英

在factory_girl 4.1中具有has_and_belongs_to_many关联

[英]has_and_belongs_to_many associations in factory_girl 4.1

我是factory_girl的新手,并试图弄清楚如何有效地为以下模型生成工厂:

class Company < ActiveRecord::Base
    has_and_belongs_to_many :tags
end

class Tags < ActiveRecord::Base
    has_and_belongs_to_many :companies

    validates :type , :inclusion => { :in => %w(market location) } 
end

我已经查看了关于StackOverflow的先前答案(包括答案),但是其中大多数已经过时和/或没有对该问题的正确答案。 有没有人可以用Factorygirl帮助定义这两个对象的工厂?

更新资料

到目前为止,这是我提出的

FactoryGirl.define do
factory :tag do
    id  448
        trait :market do
        type "market"
    end
    trait :location do
        type "location"
    end
    name "software"
end

factory :company do
    id  1234
    name "Apple Inc."
    factory :company_with_tags do
        #setting the default # of tags for companies
        ignore do
            tag_count   2
        end

            after(:create) do |company , evaluator|
                FactoryGirl.create_list(:tag , evaluator.tag_count , company: company)
            end 
    end
end
end

我认为问题是关联名称指定不正确。 Tag有很多公司,而没有一个,所以:

after(:create) do |company , evaluator|
  FactoryGirl.create_list(:tag , evaluator.tag_count , companies: [company])
end

附带说明一下,除非您试图建立多态关系,否则要避免使用type作为列名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM