2013-08-19 69 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