2013-04-22 136 views
3

使用Rails 3.2。我的模型嵌套在這樣一種方式:急切加載不同嵌套多態

  • 回顧=>應審查(國家或店鋪)
  • 國家=> CountryDay =>商店=>照片
  • 店=>照片

我有以下幾點:

@reviews = @user.reviews.includes(:user, :reviewable) 

通常我們可以以這樣的方式包括嵌套多態:

# this will return errors because :shop is not found in the model Shop (:reviewable is actually :shop) 
@reviews = @user.reviews.includes(:user, :reviewable => [:shop]) 

# this will return errors because :photos is not directly associated to Country 
@reviews = @user.reviews.includes(:user, :reviewable => :photos) 

還有很多其他的變體。我如何解決它以讓ActiveRecord根據其關聯包含正確的模型?

回答

1

我想我剛纔有同樣的問題。試圖加載關聯時,我得到了一個ActiveRecord::EagerLoadPolymorphicError。我的解決方案是將一個自定義連接語句放到一個範圍內,以方便使用。

未經檢驗的,但是這可能讓你去:

class Review < ActiveRecord::Base 
    scope :eagerly_loaded, -> { 
    joins(' 
     INNER JOIN shops 
     ON (reviews.reviewable_type = "Shop" AND reviews.reviewable_id = shops.id) 
     INNER JOIN countries 
     ON (reviews.reviewable_type = "Country" reviews.reviewable_id = countries.id) 
    ') 
    } 
end 

然後,您使用@user.reviews.eagerly_loaded。請確保使用匹配的.group()-表達式來獲得您需要的結果。