Rails 设置具有关联属性的工厂字段

Rails set factory field with an association attribute

我有这个带有自引用关联的模型:

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。我该怎么做?

谢谢,

您可以使用 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 对象存在。可以使用 no_of_suboptions

设置要创建的 suboptions 的数量

Gemfile

faker gem 添加到您的 Gemfile。

group :development, :test do
  gem 'faker'
end