'To show your comment first if you are logged (and if you left a comment)

I am editing a Book-page improving the Comments-Area.

Now it is a "classic" area where the latest 3 comments are showed.

But I want to edit it showing first the comment left by the "logged user" (current_user), if it is logged and if he already left a comment in this page, and then the others (excluding the comment by current user already showed).

Now they are showed using a script in book_controller.rb

  def load_comments!
    @comments = @book.comments.roots.includes(:user).latest.limit(3)
  end

As I said, I have to check if the user is logged and if he already left a comment.

But I don't know how to merge then the two queries.

So my first idea was to add first if current_user

  def load_comments!
    @comments = if current_user
                   @book.comments.roots.includes(:user).where(user: current_user).latest.limit(1).any?
                   + @book.comments.roots.includes(:user).where(user: !current_user).latest.limit(2) 
                else
                   @book.comments.roots.includes(:user).latest.limit(3)
                end
  end


Solution 1:[1]

What you're doing won't actually work since the where clause would apply to all the comments.

The most straight forward solution is to just perform a separate query and concatenate the arrays:

def last_user_comment
  current_user.comments
              .order(created_at: :desc)
              .where(book: @book)
              .last if current_user
end

def load_comments!
  @comments = @book.comments.roots.then do |base|
    if last_user_comment
      base.limit(2).to_a.unshift(last_user_comment)
    else
      base.limit(3)
    end
  end 
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1