检索中给定用户评论的所有帖子,Ruby on Rails的 [英] Retrieve all posts where the given user has commented, Ruby on Rails

查看:82
本文介绍了检索中给定用户评论的所有帖子,Ruby on Rails的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户,文章和评论。用户可以发布只有一个评论,以每个岗位。

I have users, posts and comments. User can post only one comment to each post.

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

在userpage(的http://主机/用户/ 1 为例)我想说明中给定用户评论所有文章。然后,每个职位将所有其他意见。

On userpage (http://host/users/1 for example) I want to show all posts where the given user has commented. Each post then will have all other comments.

我可以做这样的事情在我的用户控制器:

I can do something like this in my User controller:

def show
  @user = User.find(params[:user_id])
  @posts = []
  user.comments.each {|comment| @posts << comment.post}
end

这样,我会找到用户,那么他所有的意见,那么相应的后每个注释,然后(在我看来),每篇文章我将呈现post.comments。我在Rails的全新的,这样我就可以做到这一点=),但我认为这是莫名其妙地坏的,有一个更好的方式来做到这一点,也许我应该使用范围或named_scopes(还不知道这是什么,但看起来可怕的)。

This way I will find User, then all his comments, then corresponding post to each comment, and then (in my view) for each post I will render post.comments. I'm totally new in Rails, so I can do this =) But I think it's somehow bad and there is a better way to do this, maybe I should use scopes or named_scopes (don't know yet what this is, but looks scary).

所以,你点我出到正确的方向吗?

So can you point me out to the right direction here?

在此先感谢您的帮助。

伊利亚

推荐答案

您可以定义哪些检索所有在单个查询意见职位的关联。保持它在模型降低你的控制器的复杂性,使您能够重复使用的关联,并且更容易进行单元测试。

You could define an association which retrieves all the posts with comments in a single query. Keeping it in the model reduces the complexity of your controllers, enables you to reuse the association and makes it easier to unit test.

class User < ActiveRecord::Base
  has_many :posts_with_comments, :through => :comments, :source => :post
  # ...
end

:通过的has_many 一个选项来指定一个连接表,通过它来进行查询。我们需要指定:源和Rails就无法推断来源:post_with_comments

:through is an option for has_many to specify a join table through which to perform the query. We need to specify the :source as Rails wouldn't be able to infer the source from :post_with_comments.

最后,更新您的控制器使用的关联。

Lastly, update your controller to use the association.

def show
  @user  = User.find(params[:user_id])
  @posts = @user.posts_with_comments
end

要了解更多关于:通过:源看看的<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many"相对=nofollow>文档。

To understand more about :through and :source take a look at the documentation.

这篇关于检索中给定用户评论的所有帖子,Ruby on Rails的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆