2012-06-30 37 views
0

我有一個以類表示的內容模型:內容。現在用戶可以費率內容,查看內容或者兩者兼而有之。我想查找用戶擁有的所有內容評分,評論評分和評論評論表格與表格(表示內容可以多次查看)具有內容的多對一關聯。 評分表格和內容表格之間存在類似關係。導軌中的2個活動記錄關係對象的聯合3

我在想,我應該做單獨的查詢,以查找用戶的所有評級內容,然後由用戶查看所有評論的內容,然後進行聯合。但我找不到如何做一個返回活動記錄關係的聯合。我需要一個關係,因爲我想分頁結果。

謝謝。

回答

2

好的,首先我們來設置你的模型。你的說明,我想你會想是這樣的:

class Content < ActiveRecord::Base 
    has_many :reviews 
    has_many :reviewing_users, :through => :reviews, :class_name => "User" 

    has_many :ratings 
    has_many :rating_users, :through => :ratings, :class_name => "User" 
end 

class User < ActiveRecord::Base 
    has_many :reviews 
    has_many :reviewed_contents, :through => :reviews, :class_name => "Content" 

    has_many :ratings 
    has_many :rated_contents, :through => :ratings, :class_name => "Content" 
end 

class Review < ActiveRecord::Base 
    belongs_to :content 
    belongs_to :user 
end 

class Rating < ActiveRecord::Base 
    belongs_to :content 
    belongs_to :user 
end 

然後給定用戶,你可以找到所有他們已經審查和/或額定電壓與內容:

(user.reviewed_contents + user.rated_contents).uniq 
+0

嘿,非常感謝。我會嘗試並更新。 – berto77

+1

對不起,花了很長時間才找回來。但是,這工作完美。非常感謝。 – berto77

+0

不客氣:) – smathy

2

(user.reviewed_contents + user.rated_contents).uniq返回一個數組,而不是一個關係,所以要小心。您可以通過嘗試調用@posts(paginate除外)上的類方法來測試此功能。

雖然你仍然可以分頁。只需使用@posts.paginate,因爲will_paginate寶石添加了paginate方法到數組類。