Factory Girl:如何设置has_many/through关联

cma*_*n77 29 bdd ruby-on-rails factory-bot

我一直在努力与has_many/throughFactory Girl 建立关系.

我有以下型号:

class Job < ActiveRecord::Base
  has_many :job_details, :dependent => :destroy
  has_many :details, :through => :job_details
end

class Detail < ActiveRecord::Base
  has_many :job_details, :dependent => :destroy
  has_many :jobs, :through => :job_details
end

class JobDetail < ActiveRecord::Base
  attr_accessible :job_id, :detail_id
  belongs_to :job
  belongs_to :detail
end
Run Code Online (Sandbox Code Playgroud)

我的工厂:

factory :job do
  association     :tenant
  title           { Faker::Company.catch_phrase }
  company         { Faker::Company.name }
  company_url     { Faker::Internet.domain_name }
  purchaser_email { Faker::Internet.email }
  description     { Faker::Lorem.paragraphs(3) }
  how_to_apply    { Faker::Lorem.sentence }
  location        "New York, NY"
end

factory :detail do
  association :detail_type <--another Factory not show here
  description "Full Time"
end

factory :job_detail do
  association :job
  association :detail
end
Run Code Online (Sandbox Code Playgroud)

我想要的是我的工作工厂创建默认Detail为"全职".

我一直试图遵循这个,但没有任何运气: FactoryGirl有很多通过

我不确定如何after_create通过JobDetail附加详细信息.

Log*_*man 32

尝试这样的事情.您想构建一个detail对象并将其附加到作业的详细关联.使用时after_create,创建的作业将生成块.因此,您可以使用FactoryGirl创建详细信息对象,并将其直接添加到该作业的详细信息中.

factory :job do
  ...

  after_create do |job|
    job.details << FactoryGirl.create(:detail)
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是旧的,但是在FactoryGirl中你现在使用格式为`after(:create)`而不是`after_create`的回调.其余的答案应该仍然可以正常工作. (12认同)
  • 好的,这适用于create,因为有一些ID可供JobDetail引用,但是`after(:build)`之后呢?有没有未保存对象关联的方法?或者我应该放弃以这种方式工作的想法? (4认同)