2013-08-19 71 views
0

我已经连接了两个查询结果并希望根据特定条件限制结果。Rails级联查询结果“其中”

def all_notifications 
    return (user_project_notifications+followed_comments).sort_by(&:created_at).reverse 
end 

我想通过限制那些all_notifications一定时间后到来,所以像:

def new_notifications(notifications_last_viewed) 
    return all_notifications.where('created_at >?, notifications_last_viewed) 
end 

但是,我得到Array的错误未定义的方法',其中” :...

如何在连接结果上执行“where”查询?

回答

1

你不能直接这样做,因为你申请的典型Array(或Enumerable)方法之一后(例如“+”),它返回Array实例,该实例没有ActiveRecord方法。

我想你应该在一个查询中与“OR”取你的user_project_notificationsfollowed_comments - 那么你将有ActiveRecord::Relation情况下,可以在其上调用范围方法,如orderwhere

+0

好的,我明白了。现在要弄清楚如何从activerecord查询获得followed_comments ... – scientiffic

3

你不是做一个数据库排序,替换:

(user_project_notifications+followed_comments).sort_by(&:created_at).reverse 

有:

(user_project_notifications + followed_comments).order('created_at DESC') 

您将密切关系,而不是得到一个数组的。

我想这个问题源于+你总结数组,而你应该加入查询。

的一个好办法做到这一点是在ActiveRecord::Relation使用this gem

+0

我原来是这样的,但是我得到错误“未定义的方法”顺序'阵列“。这就是为什么我最终使用排序和反向。 – scientiffic

+0

避免查询数据库以便链接查询很重要。我猜这个问题来自''''你在那里总结数组,而你应该加入查询。一个很好的方法是使用这个宝石:https://github.com/oelmekki/activerecord_any_of – apneadiving

+0

-1解释? – apneadiving