检索给定用户发表评论的所有帖子,Ruby on Rails
我有用户、帖子和评论。用户只能对每个帖子发表一条评论。
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
在用户页面(例如 http://host/users/1
)上,我想显示给定用户发表评论的所有帖子。每个帖子都会有所有其他评论。
我可以在我的用户控制器中执行类似的操作:
def show
@user = User.find(params[:user_id])
@posts = []
user.comments.each {|comment| @posts << comment.post}
end
这样我将找到用户,然后是他的所有评论,然后是每个评论的相应帖子,然后(在我看来)对于每个帖子,我将呈现 post.comments。我对Rails完全陌生,所以我可以做到这一点=)但我认为这有点糟糕并且有更好的方法来做到这一点,也许我应该使用范围或named_scopes(还不知道这是什么,但看起来可怕的)。
那么你能指出我正确的方向吗?
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
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以定义一个关联,在单个查询中检索带有评论的所有帖子。将其保留在模型中可以降低控制器的复杂性,使您能够重用关联并使单元测试变得更容易。
:through
是has_many
的一个选项,用于指定通过其执行查询的连接表。我们需要指定:source
,因为 Rails 无法从:post_with_comments
推断源。最后,更新您的控制器以使用关联。
要了解有关
:through
和:source
的更多信息,请查看 文档。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.
:through
is an option forhas_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.
To understand more about
:through
and:source
take a look at the documentation.当您获得用户时,您就拥有了与他的帖子的关联,并且每个帖子都有他的评论。
你可以写:
(我不知道你的表字段的名称,所以我将文本命名为text)
我还没有测试代码,所以可能会有一些错误。
When you got the user, you have the associations to his posts and each post has his comments.
You could write:
(I don't know the names of your table fields, so i named the text text)
I haven't tested the code, so there could be some errors.