簡體   English   中英

factory_girl-關聯,rails中的多態

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM