factory_girl - 关联,rails中的多态

时间:2014-09-24 19:10:04

标签: ruby-on-rails factory-bot rspec-rails polymorphic-associations

我有以下轨道模型关系,工厂女孩工厂定义不正确并给出错误。

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)

任何修正工厂定义的指示都会有所帮助。

1 个答案:

答案 0 :(得分:1)

水果厂不正确。

语法:     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工厂下方。这样就可以在调用水果工厂时定义这些工厂。