[英]factory_girl - associations , polymorphic in rails
我具有以下rails模型关系,对于这些关系,工厂女孩的工厂定义没有正确并给出错误。
class MediaFile < ActiveRecord::Base
belongs_to :admin
end
class MediaFileMapping < ActiveRecord::Base
belongs_to :media_file
belongs_to :admin
belongs_to :mediable, :polymorphic => true
end
class Image < MediaFile
has_attached_file :media
# and other things
end
class ImageMapping < MediaFileMapping
end
class Fruit < ActiveRecord::Base
belongs_to :product
has_many :image_mappings, :as => :mediable
has_many :images, :class_name => "Image", :through => :image_mappings, :source => :media_file
# and other things here
end
class Product < ActiveRecord::Base
has_many :fruits, :dependent => :destroy
# other things here
end
我为此而努力写工厂。 这是最后一次给出错误的尝试
尝试的工厂定义如下
FactoryGirl.define do
factory :product do
fruit
end
factory :fruit do
association :image_mapping, factory: :media_file_mapping
association :image
end
factory :image, class: Image, parent: :media_file do
end
factory :image_mapping, class: ImageMapping, parent: :media_file_mapping do
end
factory :admin do
end
factory :media_file do
association :admin
end
factory :media_file_mapping do
media_file
admin
end
end
通过工厂创建新产品时,出现以下错误
undefined method `image_mapping=' for #<Fruit:0xbcb8bfc> (NoMethodError)
修正工厂定义的任何指导都将有所帮助。
水果工厂不正确。
语法:association:image_mapping,factory::media_file_mapping可以用于belongs_to关联。
当您处理has_many关联(这种情况)时,您需要在工厂定义中手动添加关联的记录。 一个例子:
factory :fruit do
after(:create) do |fruit|
fruit.image_mappings << FactoryGirl.create(:image_mapping)
fruit.images << FactoryGirl.create(:image)
end
fruit.save
end
您可能还应该移动水果工厂,使其位于image_mapping和image工厂下面。 这样,将在调用水果工厂时定义这些工厂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.