新手问题 请教:如何在循环显示所有的 posts 时,并且显示当前用户对 post 的 comment 内容

xdoc · March 26, 2017 · Last by darkbaby123 replied at March 28, 2017 · 1850 hits

请教:

有三个 model,分别为:user, post, comment

可能需要的信息

Model

# modle/user.rb
has_many :comments
has_many :posts through :comments

# modle/post.rb
has_many :comments

# modle/comment.rb
belongs_to :user
belongs_to :post

Controller

@posts = Posts.all

View

<%= @posts.each do |post| %>
  <%= post.name %>
  <%= 问题:如何在这里将当前用户评论的内容显示出来 %>
<% end %>

已经试过

尝试在 Controller 中用 @comments = current_user.comments.find_by(post_id: @post.id)

这是可以根据 post.id 来获取当前用户对指定 post 的评论,但却不用解决我的问题

如何在循环显示所有的 posts 时,并且显示当前用户对 post 的 comment 内容?

controller:

@comments_by_curr_user = Comment.
    where(post_id: @post.ids). # 若有分页
    where(commenter: current_user).
    group_by(&:post_id)

view:

<%= @posts.each do |post| %>
    <%= post.name %>
    <% @comments_by_curr_user[post.id].each do |comment| %>
          partial .............
    <% end %>
<% end %>

多谢热心回复,我等下测试一下。

就是有个地方不太明白

where(post_id: @post.ids). # 若有分页

这一句是如何理解,分页是指 post 吗?

三个表有关联 可以用 includes 或者 join

太好了,可以的,测试通过!!

多谢多谢

刚才查了一会才知道 group_by(&:post_id) 中的 & 的用法,它是 Ruby 中的用法,它会在后面的对象上调用 to_proc 方法。 但对整体还是不太理解。

大侠,能把思路说一下吗?为什么会想到这样用

Reply to pathbox

能否详细说一下,刚学习 Rails 不久

Reply to xdoc

请看 rails guide

Reply to pathbox

不能吧

joins 的话会出现重复 post 和漏 post(不是所有 post 都有 comment 和 user)

includes 会查出多余 comment,之后还要在 ruby 中 filter

还是说有什么特别写法?(我新手……)

includes 加条件也许可以:

Post.includes(:comments).where('comments.user_id = ?', current_user.id).references(:comments)

参见 Rails 文档

You need to Sign in before reply, if you don't have an account, please Sign up first.