我有 2 个模型,产品和类别。
产品具有 category_id
属性。所以,Product属于Category,Category有很多Products。
<!-- language: rb -->
class Product < ActiveRecord::Base
belongs_to :category
validates :category, presence: true
end
class Category < ActiveRecord::Base
has_many :products
end
如何为这两种模型定义工厂(FactoryGirlrails)?如何对产品模型执行此操作特别有趣。
最佳答案
您可能想要使用两种方案。
如果您不需要与产品关联的特定类别:
FactoryGirl.define do
factory :category do
# category fields
end
factory :product do
# other product fields here
category
end
end
然后您可以create(:product)
,它会在创建时获得分配给它的新类别。
如果您需要在产品中重复使用已知类别:
在这种情况下,您需要显式创建对象。您可以使用上面相同的工厂,但创建它们如下:
category = create(:category)
product = create(:product, category: category)
这样您就可以为多个产品重复使用该类别,或分别操作这两个产品。
关于ruby-on-rails - FactoryGirl 与协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14511609/