class Food < ActiveRecord::Base
has_many :images, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy
end
class MenuPhoto < ActiveRecord::Base
has_one :image, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy
end
class Image < ActiveRecord::Base
belongs_to :imageable, foreign_key: :imageable_uuid, :polymorphic => true
end
我在上面的这些模型中使用了多态。所以在我的工厂女孩中,我是这样做的。
factory :food do
association :images, factory: :image
end
factory :menu_photo do
association :image, factory: :image
end
factory :image do
photo { fixture_file_upload(Rails.root.join("spec", "fixtures", "pass.jpg"), "image/jpg") }
end
当我在 Rails 控制台测试环境中使用“FactoryGirl.create(:menu_photo)”进行测试时,它工作正常。它创建了 :menu_photo 和 :image。 但是当我用“FactoryGirl.create(:food) ”运行它时,它会出错: NoMethodError:#
的未定义方法“each”最佳答案
我认为问题在于您正在尝试为 has_many 关联设置单个图像。如果你这样做会怎样:
factory :food do
after(:create) { |f|
f.images.create!()
}
end
关于ruby-on-rails - Factory Girl 多态 has_many, belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13225255/