工厂女孩:如何建立has_many/through关联 [英] Factory Girl: How to set up a has_many/through association
问题描述
我一直在努力使用Factory Girl建立has_many/through
关系.
I've been struggling with setting up a has_many/through
relationship using Factory 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
我的工厂:
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
我想要的是在默认Detail
为全职"的情况下创建我的工作工厂.
What I want is for my job factory to be created with a default Detail
of "Full Time".
我一直在尝试遵循此方法,但是没有任何运气: FactoryGirl有很多通过
I've been trying to follow this, but have not had any luck: FactoryGirl Has Many through
我不确定应如何使用after_create
通过JobDetail附加明细.
I'm not sure how the after_create
should be used to attach the Detail via JobDetail.
推荐答案
尝试类似的方法.您要构建一个detail
对象,并将其附加到作业的详细信息关联中.当您使用after_create
时,创建的作业将被屈服于该块.因此,您可以使用FactoryGirl创建一个明细对象,并将其直接添加到该作业的明细中.
Try something like this. You want to build a detail
object and append it to the job's detail association. When you use after_create
, the created job will be yielded to the block. So you can use FactoryGirl to create a detail object, and add it to that job's details directly.
factory :job do
...
after_create do |job|
job.details << FactoryGirl.create(:detail)
end
end
这篇关于工厂女孩:如何建立has_many/through关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!