2012-03-23 74 views
12

我有一個產品,產品可以有很多圖像。這是通過關聯表。但是,我希望產品有一個主要圖像。rails has_one of has_many association

我知道這很容易用模型中的方法來做,但我希望它是一個關聯,以便我可以使用include在查詢中預加載它。

型號:

class Product < ActiveRecord::Base 
    has_many :image_associations, :as => :imageable 
    has_many :images, :through => :image_associations 
end 

class ImageAssociation < ActiveRecord::Base 
    belongs_to :image 
    belongs_to :imageable, :polymorphic => true 
end 

class Image < ActiveRecord::Base 
    has_many :image_associations 
end 

在ImageAssociation表中,有一個稱爲「功能」布爾列其中圖像作爲「主」圖像關聯。

一個我想過這樣做是添加main_image_id列的產品表,然後添加到Image模型的方法:

belongs_to :image, :class => "Image", :foreign_key => "main_image_id" 

然而,這不允許任何後備到另一個has_many圖像,如果主圖像爲零 - 我希望關聯加載。

這就是爲什麼我希望的東西在圖像模型,如:

has_one :image, :through => :images, :conditions => 'feature = true', :order => 'created_at DESC' 

但是,這給了我一個關聯錯誤。

有沒有什麼辦法可以編輯has_one,還是我真的需要運行rake任務來將圖像推送到每個main_image_id字段,然後添加未來產品的驗證以確保已添加主圖像?

編輯:

我應該使用一個has_and_belongs_to_many的關聯呢?

回答

13

你幾乎在那裏,我想,雖然我不太清楚多態關聯。我想你想要以下內容:

has_one :main_image_assoc, class => "ImageAssociation", :conditions => 'feature = true', :order => 'created_at DESC', :as => :imageable 
has_one :image, :through => :main_image_assoc 
+0

沒有。如果需要,您可以使用集合的其他過濾has_many關聯執行此操作,但不指定has_one。發生此錯誤:'ActiveRecord :: HasOneThroughCantAssociateThroughCollection:不能有has_one:通過關聯'article#image'其中:通過關聯'Article#image_associations'是一個集合。改爲在:through選項中指定has_one或belongs_to關聯。「已經嘗試過。 – 2012-03-23 13:59:58

+0

啊,我可以看到。讓我試一下編輯。 – Chowlett 2012-03-23 14:06:51

+1

更正到第一行:':has_one:main_image_assoc,:class_name =>「ImageAssociation」,:order =>'feature = true',:as =>:imageable' ...這允許回退(以及正確的語法) 。謝謝! – 2012-03-23 14:35:09