藝術家有許多活動(基本上是用戶之間的交互的高速緩存):有沒有辦法來加載多態關聯的關聯?
class Activity < ActiveRecord::Base
belongs_to :receiver, :class_name => 'Artist', :foreign_key => :receiver_id #owns the stuff done "TO" him
belongs_to :link, :polymorphic => true
belongs_to :creator, :class_name => 'Artist', :foreign_key => :creator_id #person who initiated the activity
end
例如:
Activity.create(:receiver_id => author_id, :creator_id => artist_id, :link_id => id, :link_type => 'ArtRating')
我想爲每位藝術家創建活動流頁面,包括列表不同類型的事件,ArtRatings(喜歡,不喜歡的),收藏,繼等
控制器看起來是這樣的:
class ActivityStreamController < ApplicationController
def index
@activities = @artist.activities.includes([:link,:creator,:receiver]).order("id DESC").limit(30)
end
end
的DB調用正確急切地加載多態鏈接對象:
SELECT "activities".* FROM "activities" WHERE (("activities"."receiver_id" = 6 OR "activities"."creator_id" = 6)) ORDER BY id DESC LIMIT 30
ArtRating Load (0.5ms) SELECT "art_ratings".* FROM "art_ratings" WHERE "art_ratings"."id" IN (137, 136, 133, 130, 126, 125, 114, 104, 103, 95, 85, 80, 73, 64)
SELECT "follows".* FROM "follows" WHERE "follows"."id" IN (14, 10)
SELECT "favorites".* FROM "favorites" WHERE "favorites"."id" IN (25, 16, 14)
但是,當我顯示每個ArtRating,我還需要引用的文章標題,這屬於一個職位。在我看來,如果我這樣做:
activity.link.post
它爲每個art_rating的文章做一個單獨的數據庫調用。有沒有辦法熱切地加載帖子?
更新的問題:
如果沒有辦法使用,實現職位的渴望加載「包括」語法,有沒有辦法做手工的預先加載查詢自己和它注入@活動對象?
我在數據庫日誌中看到:
SELECT "art_ratings".* FROM "art_ratings" WHERE "art_ratings"."id" IN (137, 136, 133, 130, 126, 125, 114, 104, 103, 95, 85, 80, 73, 64)
有沒有一種方法,我可以訪問來自@activities IDS的這個列表對象?如果是這樣,我可以做2個附加查詢,其中1個獲取該列表中的art_ratings.post_id(s),另一個查詢將這些post_ids中的所有帖子選中。然後以某種方式將'post'結果注入到@activities中,以便在遍歷集合時作爲activity.link.post提供。可能?
這裏有什麼進展? – bogardon 2013-10-06 22:24:19
從我所瞭解的情況來看,你有一套應該作爲鏈接附加到活動上的模型,我收集他們都至少共享一個關聯,這是'post'。這些鏈接模型中是否有足夠的共同點來使用[單表繼承](http://apidock.com/rails/ActiveRecord/Base)並將所有表放在一個表中? – CMW 2013-10-25 13:03:36