2014-11-05 28 views
0

我有多个关联:关联名字找不到,也许你拼错了吗?

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宝石,当我做这在我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? 

即使当我尝试这样做香草版本:

@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),因为我使用的子弹宝石,试图追查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

你试过使用复数节点吗?因为这就是它的定义在你的has_many – CambridgeMike 2014-11-05 22:08:19

+0

是......我也试过:'ActiveRecord :: AssociationNotFoundError at/ 在Notification上找不到名为'nodes'的关联;也许你拼错了吗?' – marcamillion 2014-11-06 11:05:05

回答

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])

这似乎已经奏效精美。

0

Node是您的trackable对象在PublicActivity条款。这是一个多态关联,可以让您使用您的Node类以及任何其他模型。

这就是为什么你应该尝试includes(:trackable)来代替。以控制器为例:@unread_act = Notification.where(owner_id: current_user).includes(trackable: { user: :nodes}).unread_by(current_user)

另请注意,您从PA::Activity中派生出自己的Notification类,这可能无法与acts_as_readable一起使用。试试p_a wiki以了解如何扩展课程。

+0

我试过了,但我仍然遇到N + 1问题 - 这就是为什么我试图eager_load所有这些对象。关于如何在一次调用中加载:node,:user和:trackable的任何想法? – marcamillion 2014-11-06 15:24:24

+0

我更新了这个问题,并详细介绍了我试图压扁的'n + 1'问题。 – marcamillion 2014-11-06 15:58:25

+0

另外我没有在p_a wiki上看到任何文章,告诉你如何扩展这个类 - https://github.com/pokonski/public_activity/wiki。你有没有具体的一点,你可以指点我? – marcamillion 2014-11-06 16:40:27