如何使用Fabricate-gem生成对象?

How to use Fabricate-gem to generate objects?

我正在使用 Rails 4,Fabricate and Faker Gems. And I'm trying to seed my database with (100 or so) randomly created objects (Order that contains up to 3 Ice Creams). I followed This Answer 推荐使用这种方法。

models/order.rb

  class Order < ActiveRecord::Base
    ...
    has_many :ice_creams
    ...
  end

models/ice_cream.rb

  class IceCream < ActiveRecord::Base
    ...
    has_and_belongs_to_many :flavors
    has_many :added_extras
    has_many :extras, :through => :added_extras
    belongs_to :order
    ...
  end

models/extra.rb

  class Extra < ActiveRecord::Base
    ...
    has_many :added_extras
    has_many :extras, :through => :added_extras
    ...
  end

test/fabricators/order_fabricator.rb

  Fabricator(:order) do

    user { User.offset(rand(User.count)).first } #fine
    shift { Shift.offset(rand(Shift.count)).first } #fine
    created_at { Faker::Date.backward(365) } #fine
    ice_creams(rand: 3) { |attrs| Fabricate( :ice_cream, created_at: attrs[:created_at] ) } #fine

    total { Faker::Number.between(5, 25) }
    #add more logic depending of the total number of randomly created ice creams

    discount { [0, 10, 15, 25].sample } #fine
    total_after_discount { |order| order[:total] -  ( (order[:total] * order[:discount]) / 100 ) }
    paid { [50, 100, 200].sample } #fine
    remaining { |order| order[:paid] -  order[:total_after_discount] } #fine

  end

test/fabricators/ice_cream_fabricator.rb

  Fabricator(:ice_cream) do

    size { Size.offset(rand(Size.count)).first } #fine
    basis { Basis.offset(rand(Basis.count)).first } #fine
    sauce { Sauce.offset(rand(Sauce.count)).first } #fine
    topping { Topping.offset(rand(Topping.count)).first } #fine

    flavors { [ Flavor.offset(rand(Flavor.count)).first ] }
    #add additional ability to be one or two flavors randomly

    extras { [ Extra.offset(rand(Extra.count)).first ] }

    ice_cream_price { [15, 17, 18, 19, 20, 22].sample } #add logic
    extras_price { [5, 10, 15, 20 ].sample } #add logic 

    total_price { |attrs| attrs[:ice_cream_price] + attrs[:extras_price] } #fine
    created_at { Faker::Date.backward(365) }

  end

工作正常,我现在可以创建最多包含 3 个假 冰淇淋 的假 Orders,但问题是我努力弄清楚制造更现实的逻辑订单,正如您可能在我的制造商代码中注意到的那样,我标记了一些属性很好-我对它的结果很好-还有一些我仍然不完全满意,喜欢...

我已经尝试通过创建一个 Flavor Fabricator 来做到这一点,但它没有用..

test/fabricators/flavor_fabricator.rb

  Fabricator(:flavor) do
    Flavor.offset(rand(Flavor.count)).first
  end

我也试过总结:total_price activeRecord 的方式,但是也没用

test/fabricators/order_fabricator.rb

  Fabricator(:order) do
    ...
    total { self.ice_creams.sum(:total_price) }
    ...
  end

所以我的问题是…… - 我想要的东西是可能的还是太多了?如果可以,如何实现?

我希望我说清楚了,你可以帮助我。谢谢

您似乎在尝试使用制造来设置模型的计算值,例如 IceCream#total_price。你应该让你的模型上的方法做他们的事情,比如从部分计算总数,而不是试图通过制造来强迫它们。

具体回答您的问题:

1)我希望人造冰淇淋可以-随机-有一种或两种口味。

Fabricator(:ice_cream) do
  flavors { Flavor.all.sample(rand(1..2)) }
end

2) 同#1

3) 你应该在 Order 上有一个在创建时计算总数的方法。