Rails使用关联属性设置工厂字段

时间:2017-01-11 00:45:49

标签: ruby-on-rails factory-bot

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

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。我怎么能这样做?

谢谢,

1 个答案:

答案 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