在我的种子文件中,我有以下几点:
Product.create([
{
:description => "something something",
:goals =>
[
Goal.find_by_name("Healthy Living"),
Goal.find_by_name("Build Muscle")
],
:variations_attributes =>
[
{
:flavor => Flavor.find_by_flavor("Vanilla"),
:price => 49.99,
},
{
:flavor => Flavor.find_by_flavor("Chocolate"),
:price => 29.99,
}
]
}])
我会建立一个模仿这个记录的工厂吗?我在github上为工厂女孩读了一篇“入门”读物,但是我仍然很难创造像这样的工厂。任何帮助,将不胜感激。感谢。
产品模型如下:
class Product < ActiveRecord::Base
attr_accessible :active, :goal_id, :description, :gender_id, :name, :internal_product_id, :image, :image_cache, :brand, :variations
attr_protected nil
belongs_to :gender
has_many :variations, :dependent => :destroy
has_many :product_goals
has_many :goals, :through => :product_goals
accepts_nested_attributes_for :variations, :reject_if => lambda { |a| a[:price].blank? }, :allow_destroy => true
mount_uploader :image, ImageUploader
def flavors
# return the set of available flavors
# this method is necessary because flavors are associated
# with variations, not the product itself
self.variations.collect{|v| v.flavor}.uniq.sort_by{|f| f.flavor}
end
end
答案 0 :(得分:1)
您可以在工厂中添加其他有效工厂。类似的东西:
after(:create) { |product| product.variations << FactoryGirl.create(:flavor) }
after(:create) { |product| product.goals << FactoryGirl.create(:goal) }