我有一个带有自引用关联的模型:
class Option < ApplicationRecord
belongs_to :activity
has_many :suboptions, class_name: "Option"
belongs_to :parent, class_name: "Option", optional: true
end
我想创建一个子选项工厂(使用FactoryGirl),其中activity_id
等于父activity_id
。我怎么能这样做?
谢谢,
答案 0 :(得分:2)
您可以使用after(:build)
和after(:create)
回调,如下所示。
FactoryGirl.define do
factory :option do
transient do
parent_option nil
no_of_suboptions nil
end
name Faker::Internet.name
after(:build) do |option, evaluator|
#option.activity_id = evaluator.activity.id
if not evaluator.parent_option.blank?
#option.parent_id = evaluator.parent_option.id
option.parent = evaluator.parent_option
end
end
factory :option_with_suboptions do
after(:create) do |option, evaluator|
create_list(:option, evaluator.no_of_suboptions, :activity => option.activity, :parent => option)
end
end
end
end
<强>用法强>
FactoryGirl.create(:option_with_suboptions, :activity => activity, :no_of_suboptions => 5)
需要确保activity
对象存在。可以使用suboptions
no_of_suboptions
个数
<强>的Gemfile 强>
将faker
gem添加到您的Gemfile中。
group :development, :test do
gem 'faker'
end