xxyyxx
xxyyxx

Reputation: 2396

How do I write a factory for a model with nested attributes?

In my seeds file I have something along the lines of:

 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,
              }
            ]

    }])

I would I go about building a factory to mimic this record? I went through the "getting started" read-me on github for factory girl, but I', still having difficulties creating more advances factories like this one. Any help would be appreciated. Thanks.

The model for Product looks like:

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

Upvotes: 0

Views: 85

Answers (1)

Adeptus
Adeptus

Reputation: 683

You can add in factory other valid factory. Something like:

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

Upvotes: 1

Related Questions