0

我有以下軌道模型的關係,工廠女童工廠定義沒有得到正確的,並給出錯誤。factory_girl - 協會,多形軌道

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

水果工廠不正確。

語法: 關聯: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和圖像工廠搬到水果工廠。這樣,當水果工廠被召喚時,這些工廠將被定義。