Ruby Rails通过两种不同的关系获取相关项
我有一个“两个中间人”模型设置,如下所示:Ruby Rails通过两种不同的关系获取相关项,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,我有一个“两个中间人”模型设置,如下所示: User has_many :comments has_many :ratings Comment belongs_to :user belongs_to :movie Rating belongs_to :user belongs_to :movie Movie has_many :comments has_many :ratings 获取用户相关的所有电影(评论或评级)的最佳方式是什么? 我希望能够调用Use
User
has_many :comments
has_many :ratings
Comment
belongs_to :user
belongs_to :movie
Rating
belongs_to :user
belongs_to :movie
Movie
has_many :comments
has_many :ratings
获取用户
相关的所有电影(评论或评级)的最佳方式是什么?
我希望能够调用User.get\u movies(User\u id)
,并返回一个ActiveRecord::Relation
对象,使其可链接(即User.get\u movies(User\u id).限制(3).顺序(…)
)。这将返回一个常规的旧数组,我怀疑我对数据库的访问超出了我的需要
def self.get_movies(user_id)
user = self.where(:id => user_id).includes({:comments => :movie}, {:ratings => :movie})
movies = []
user.comments.each do |comment|
movies.push(comment.movie)
end
user.ratings.each do |rating|
movies.push(rating.movie)
end
movies.uniq!
end
未经测试,但我非常确定使用连接
而不是包含
也可以工作
未经测试,但我非常确定使用
连接
而不是包含
也能起作用。有趣。。。虽然建立这些额外的关系让我感觉有点不舒服,但我几乎需要一些东西,比如有很多:电影,:通过=>[:评论,:收视率]
-但我很确定这不会发生exist@brittohalloran:你能试试第二个选项吗?是的,我以前也试过玩连接-你的代码只返回电影
,它们都有来自该用户的评论和评级。明白了-将。连接(…)。连接(…)
替换为。包括(:评级,:评论)
而且它工作得非常完美。返回一个关系,不包含重复项。把它修好,我会记下来作为答案。谢谢你的帮助。。。虽然建立这些额外的关系让我感觉有点不舒服,但我几乎需要一些东西,比如有很多:电影,:通过=>[:评论,:收视率]
-但我很确定这不会发生exist@brittohalloran:你能试试第二个选项吗?是的,我以前也试过玩连接-你的代码只返回电影
,它们都有来自该用户的评论和评级。明白了-将。连接(…)。连接(…)
替换为。包括(:评级,:评论)
而且它工作得非常完美。返回一个关系,不包含重复项。把它修好,我会记下来作为答案。谢谢你的帮助
def movies
Movie.includes(:ratings, :comments).where("`ratings`.user_id = ? OR `comments`.user_id = ?", self.id, self.id)
end