我很难正确设置这个 FactoryGirl 关联。
我的模型如下:
class ProductList < ActiveRecord::Base
has_many :product_list_items
has_many :product_variations, :through => :product_list_items
end
class ProductVariation < ActiveRecord::Base
has_many :product_list_items
has_many :product_lists, :through => :product_list_items
end
class ProductListItem < ActiveRecord::Base
attr_accessible :product_list_id, :product_variation_id, :quantity
belongs_to :list
belongs_to :product_variation
end
我的工厂如下:
FactoryGirl.define do
factory :product_list do
sequence(:name) { |n| "Product List {n}" }
description "Product List Description"
user
after :create do |p|
p.product_variations << FactoryGirl.create(:product_variation)
end
end
end
FactoryGirl.define do
factory :product_list_item do
association :product_list
association :product_variation
quantity { rand(1..30) }
end
end
FactoryGirl.define do
factory :product_variation do
sequence(:sku) { |n| "product_sku_#{n}" }
product
price {"#{ rand(1..30) }.#{ rand(10..99) }"}
currency "USD"
end
end
现在,当我将产品列表工厂创建为
product_list = FactoryGirl.create(:product_list)
并检查 product_list_item 的 product_list 我得到数量 = nil
product_list.product_list_items.first.inspect
#<ProductListItem id: 8, product_list_id: 8, product_variation_id: 8, quantity: nil, created_at: "2013-09-17 04:35:58", updated_at: "2013-09-17 04:35:58">
有人可以指出我哪里出错了吗?提前致谢。