0

我正在使用 Rails 4,FabricateFaker Gems。我正在尝试使用(100 个左右)随机创建的对象(包含多达 3 个冰淇淋的订单)为我的数据库播种。我遵循了推荐使用这种方法的这个答案。

模型/订单.rb

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

模型/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

模型/extra.rb

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

测试/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

测试/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 个假冰淇淋的假订单,但问题是我正在努力找出制造更真实订单的逻辑,正如您可能在我的制造商代码中注意到的那样,有一些属性我标记为很好——我对它的结果很好——还有一些我仍然不完全满意的,比如......

  • 我希望制作的冰淇淋可以随机地有一种或两种口味。
  • 我希望对 Extras 做同样的事情
  • 我想将随机制作的冰淇淋 的总和:total_price传递给订单:total

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

测试/fabricators/flavor_fabricator.rb

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

我也尝试总结了:total_priceactiveRecord的方式,但它也没有奏效

测试/fabricators/order_fabricator.rb

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

所以我的问题是... - 我希望的事情是可能的还是太多了?如果是这样,如何实现?

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

4

1 回答 1

1

例如,您似乎正在尝试使用制造来设置模型上的计算值IceCream#total_price。您应该让模型上的方法完成它们的工作,例如从零件中计算总数,而不是试图通过制造来强迫它们。

具体回答您的问题:

1)我希望制作的冰淇淋可以——随机地——有一种或两种口味。

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

2) 与#1 相同

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

于 2016-10-03T14:10:43.570 回答