【问题标题】:factory_girl - associations , polymorphic in railsfactory_girl - 关联,rails 中的多态
【发布时间】:2014-09-24 19:10:04
【问题描述】:

我有以下 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)

任何修复工厂定义的说明都会有所帮助。

【问题讨论】:

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


    【解决方案1】:

    水果工厂不正确。

    语法: 关联:image_mapping,工厂::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 factory 的下方。这样,当调用水果工厂时,就会定义这些工厂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多