Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何为具有嵌套属性的模型编写工厂?_Ruby On Rails_Factory Bot - Fatal编程技术网

Ruby on rails 如何为具有嵌套属性的模型编写工厂?

Ruby on rails 如何为具有嵌套属性的模型编写工厂?,ruby-on-rails,factory-bot,Ruby On Rails,Factory Bot,在我的seeds文件中,我有如下内容: Product.create([ { :description => "something something", :goals => [ Goal.find_by_name("Healthy Living"), Goal.find_by_name("Build Muscle") ], :variations_attri

在我的seeds文件中,我有如下内容:

 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
类产品:destroy
有很多:产品目标
有很多:目标,:通过=>:产品\u目标
接受_嵌套的_属性_for:variations,:reject _if=>lambda{a | a[:price].blank?},:allow _destroy=>true
挂载上传器:图像,图像上传器
def口味
#返回可用的口味集
#这种方法是必要的,因为口味是关联的
#有变化,而不是产品本身
self.variations.collect{v|v.flavor}.uniq.sort|u by{f|f.flavor}
结束
结束

您可以将工厂添加到其他有效工厂中。比如:

after(:create) { |product| product.variations << FactoryGirl.create(:flavor) }
after(:create) { |product| product.goals << FactoryGirl.create(:goal) }
after(:create){| product | product.variations