我有多个关联:
User
class User < ActiveRecord::Base
has_one :family_tree, dependent: :destroy
has_many :memberships, dependent: :destroy
has_many :nodes, dependent: :destroy
has_many :participants, dependent: :destroy
has_many :comments
Node
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
class Notification < PublicActivity::Activity
acts_as_readable :on => :created_at
end
我正在使用public_activity gem,当我在ApplicationController
中执行此操作时:
@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 User; perhaps you misspelled it?
即使我尝试过这款Vanilla版本:
@unread_act = Notification.where(owner_id: current_user).includes(:node).unread_by(current_user)
我收到了这个错误:
ActiveRecord::AssociationNotFoundError at /
Association named 'node' was not found on Notification; perhaps you misspelled it?
导致这种情况的原因是什么?
修改1
当我尝试执行includes(:trackable)
时,鉴于我正在使用bullet gem,尝试追踪N + 1错误,我收到了此消息:
N+1 Query detected
Node => [:user]
Add to your finder: :include => [:user]
N+1 Query detected
Node => [:media]
Add to your finder: :include => [:media]
N+1 Query method call stack
所以我正在做的就是尝试减少这些N + 1查询问题。
答案 0 :(得分:1)
似乎正确的方法是在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])
这似乎很有效。
答案 1 :(得分:0)
Node
是PublicActivity条款中的trackable
对象。它是一种多态关联,允许您使用Node
类以及任何其他模型。
这就是为什么你应该尝试includes(:trackable)
的原因。使用控制器中的示例:@unread_act = Notification.where(owner_id: current_user).includes(trackable: { user: :nodes}).unread_by(current_user)
。
另请注意,您从Notification
派生了自己的PA::Activity
课程,这可能无法与acts_as_readable一起使用。尝试使用p_a wiki来学习如何扩展课程。