2活动记录关系对象的轨道3联盟 [英] Union of 2 active record relation object in rails 3
问题描述
我有一个内容模型重新$ P $按类psented:内容。现在,用户可以率含量的评论内容的或两者都做。我想找到的所有用户都有的内容,无论的评分的审查或评分和评论的。在意见表有许多-to-one关联的内容表格(意为内容可以回顾很多次)。在收视率之间存在类似的关系表和内容表。
I have a content model represented by class: content. Now users can rate content, review content or do both. I want to find all the content that a user have either rated, reviewed or rated and reviewed. The reviews table has a many-to-one association with the content table (meaning a content can be reviewed many times). A similar relationship exists between the ratings table and the content table.
我想我应该做单独的查询,以查找用户的所有额定的内容,那么所有的某位用户的内容,然后做了工会。但我不能找出如何做到这一点返回一个有效记录关系的联合。我需要的关系,因为我想分页的结果。
I'm thinking I should do separate queries to find all rated content by a user, then all reviewed content by a user, then do a union. But I can't find out how to do a union that returns an active record relation. I need a relation because I want to paginate the results.
感谢你。
推荐答案
好了,首先让我们来设置你的模型。从你的解释我想你会想是这样的:
Ok, so first let's set up your models. From your explanation I'm thinking you'll want something like this:
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
然后给定用户,你可以说他们已经审查和/或评级与找到的所有内容:
And then for a given user you can find all the content that they've reviewed and/or rated with:
( user.reviewed_contents + user.rated_contents ).uniq
这篇关于2活动记录关系对象的轨道3联盟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!