我有以下型号:
class Productmainclass < ActiveRecord::Base
attr_accessible :name, :id, :maintext
has_many :producttaggings, :dependent => :destroy
has_many :products, :through => :producttaggings
has_many :productsubclasses
end
class Productsubclass < ActiveRecord::Base
attr_accessible :name, :id, :maintext
has_many :producttaggings, :dependent => :destroy
has_many :products, :through => :producttaggings
belongs_to :productmainclass
end
class Product < ActiveRecord::Base
attr_accessible :name, :productimage, :size, :description, :price
has_many :producttaggings, :dependent => :destroy
has_many :productsubclasses, :through => :meteoritetaggings
has_many :productmainclasses, :through => :meteoritetaggings
mount_uploader :productimage, ProductimageUploader
end
class Producttagging < ActiveRecord::Base
belongs_to :product
belongs_to :productsubclass
belongs_to :productmainclass
attr_accessible :product_id, :productsubclass_id, :productmainclass_id
end
我现在想用FactoryGirl和Capybara创建一个产品。在规范中,我只是:
product = FactoryGirl.create(:product)
在我的工厂里。我有:
factory :product do
name "Blue glass"
description "Description text of product"
productimage File.new(File.join(::Rails.root.to_s, "spec/factories/", "testimage.jpg"), 'rb')
productsubclass
productmainclass
end
factory :productsubclass do
name "Colored glasses"
productmainclass
end
factory :productmainclass do
name "Glasses"
end
运行测试我得到:
Failure/Error: product = FactoryGirl.create(:product)
NoMethodError:
undefined method `productsubclass=' for #<Product:0xcd42090>
答案 0 :(得分:1)
我认为你设置它的方式会有用,如果你处理的情况是:产品属于productsubclass,那么产品和productsubclass将使用product.productsubclass_id很好地插入创建,一切都会好的,但是这显然不是你的结构,所以我们必须采用另一种方式。我认为@depa指出的链接是正确的方法,特别是本文档中的“基本有很多关联”部分:http://robots.thoughtbot.com/aint-no-calla-back-girl尽管你有更复杂的has_many通过。但基本上你在看你创建一个对象的情况,然后你触发另一个创建来创建一个对象。希望这有道理:)
**更新**
这是另一种可能有限的方法,但您可以从另一个方向创建记录。所以,如果您只想在每个对象/表中记录一条记录:
FactoryGirl.define do
factory :producttagging do
product
productsubclass
productmainclass
end
end