2012-06-30 38 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方法到数组类。