5

我使用public_activity和我的泛音我有這個調用:由這個調用執行如何爲多個關聯進行熱切加載?

<%= link_to "#{activity.trackable.user.name} " + "commented on " + "#{activity.trackable.node.name}", node_path(activity.trackable.node.family_tree_id,activity.trackable.node) %> 

 <% @unread_act.each do |friend| %> 
     <li><%= render_activity friend %> </li> 
     <% end %> 

該實例變量是在我ApplicationController這裏分配

before_filter :handle_nofications 

    def handle_nofications 
    if current_user.present? 
     @unread_act = Notification.where(owner_id: current_user).includes(:trackable => :user).unread_by(current_user) 
    end 
    end 

我使用的寶石子彈,找到N + 1的查詢和我得到的反饋是這樣的:

N+1 Query detected 
    Comment => [:node] 
    Add to your finder: :include => [:node] 
N+1 Query method call stack 

我最初得到的消息爲:trackable:user。我現在正在通過includes在該賦值語句中進行熱切加載。

但是,我不知道如何去3層深的急切加載 - 而不是兩個。

鑑於該節點被稱爲像activity.trackable.node.name,我想一些適當的預先加載的分配會看起來像:

@unread_act = Notification.where(owner_id: current_user).includes(:trackable => [:user, :node]).unread_by(current_user) 

但我得到的錯誤是這樣的:

ActiveRecord::AssociationNotFoundError at/
Association named 'node' was not found on Node; perhaps you misspelled it? 

我甚至得到當我簡單地做:

@unread_act = Notification.where(owner_id: current_user).includes(:trackable => :node).unread_by(current_user) 

所以我懷疑東西埃爾斯這裏錯了。

任何想法?

編輯1種

請參閱節點&通知型號及以下的關聯。

Node.rb

class Node < ActiveRecord::Base 
    include PublicActivity::Model 
    tracked except: :update, owner: ->(controller, model) { controller && controller.current_user } 

    belongs_to :family_tree 
    belongs_to :user 
    belongs_to :media, polymorphic: true, dependent: :destroy 
    has_many :comments, dependent: :destroy 
    has_many :node_comments, dependent: :destroy 

Notification.rb

class Notification < PublicActivity::Activity 
    acts_as_readable :on => :created_at 
end 
+0

顯示您的模型。什麼是「通知」的「可跟蹤」關聯?什麼是「節點」的關聯? – 2014-11-05 10:08:29

+0

@MarekLipka更新的問題。 – marcamillion 2014-11-05 10:18:25

回答

0

這似乎解決這個正確的方法是使用在trackable屬性這樣一個數組:

@unread_act = Notification.where(recipient_id: current_user).includes(:trackable => [:user, :node]).unread_by(current_user).order("created_at desc") 

主要部分是:

includes(:trackable => [:user, :node])

這似乎工作得很好。