在工厂女孩/工厂机器人中,我如何为第二个查找表提供条件种子

问题描述 投票:0回答:1

我有两个类PublisherLevel和Publisher。如果我们创建发布者,则PublisherLevel计数应等于14 - 不同发布者级别类型的计数。在我们的数据库中,我们有一个外键约束。这只是一个查找表。我想做这样的事情:

FactoryGirl.define do
  if PublisherLevel.count == 0 
    puts "you have 0 publisher_levels and should seed it"
    seed_publisher_levels
  end
  factory :company do
    name { Faker::Company.name }
    display_name "Sample Company"
    publisher_level 
  end
end

但是第一个if语句没有被调用。我见过这个Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors但是已经8岁了,怀疑有更优雅的解决方案。这样做的规范方法是什么?

ruby-on-rails factory-bot
1个回答
1
投票

您似乎想要种子数据。您可以创建自己的种子类来缓存必要的数据:

class Seeds
  def [](name)
    all.fetch(name)
  end

  def register(name, object)
    all[name.to_sym] = object
  end

  def setup
    register :publisher_level_1, FactoryGirl.create(:publisher_level, :some_trait)
    register :publisher_level_2, FactoryGirl.create(:publisher_level, :some_other_trait)
  end

  private

  def all
    @all ||= {}
  end
end

然后在你的test_helper.rb中,致电:

require 'path/to/seeds.rb'
Seeds.setup

最后,在您的工厂中引用它:

factory :company do
  publisher_level { Seeds[:publisher_level_1] }
end

此代码只是一个使用示例,您必须调整它以使其根据您的需要运行。

© www.soinside.com 2019 - 2024. All rights reserved.