dimanche 15 mai 2022

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 he is logged and if he already left a comment in this page, and then the 2 others (excluding the comment by current user already showed).

If it is not logged or there are no comments left by the current_user, to show the latest 3 comments.

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.

So I was editing it in this way

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

is it good, right? It should work... but it doesn't work!! And my local host shows only "error 500", and I can not able to find the bug.

Tips?

Aucun commentaire:

Enregistrer un commentaire