这段代码的问题是什么?

时间:2016-12-22 07:15:52

标签: ruby-on-rails ruby

 class CommentsController < ApplicationController
   def users_comments 
     posts = Post.all
     comments = posts.map(&:comments).flatten
     @user_comments = comments.select do |comment|
       comment.author.username == params[:username]
     end
   end 
 end

2 个答案:

答案 0 :(得分:3)

尝试

通过将方法中的第一行更改为:

,可以避免这一切
posts = Post.includes(comments: [:user]).all

class CommentsController < ApplicationController

  def users_comments 

    posts = Post.includes(comments: [:user]).all
    comments = posts.map(&:comments).flatten
    @user_comments = comments.select do |comment|
    comment.author.username == params[:username]
  end

end

答案 1 :(得分:0)

代码中缺少end的{​​{1}},您还需要包含docomments关联以避免n + 1个查询。

author

所以代码看起来像

posts = Post.includes(comments: :author)
相关问题