I have three models: User, Comment and Upvote. User-comment is one-to-many, User-to-Upvote is one-to-many, and User-to-Upvote is one-to-many.
I want to do something similar to upvoting done in Stackoverflow. Therefore, when you raise / decrease the arrow, the arrow will stand out and remain highlighted, even if you refresh the page or return to the page days / weeks later.
I am currently doing this:
<% if Upvote.voted?(@user.id, comment.id) %> <%= link_to '^', ... style: 'color: orange;'%> <% else %> <%= link_to '^', ... style: 'color:black;'%> <% end %>
where is the voted? method voted? as follows:
def self.voted?(user_id, comment_id) find_by(comment_id: comment_id, user_id: user_id).present? end
So, if I have 10 comments per page, this will load upvote from my database 10 times, just to check if it exists!
There should be a better way to do this, but I think my brain stops working, so I can't think of it.
source share