I have three models: User, Comment and Upvote. User-to-Comment has a one-to-many relation, Comment-to-Upvote has a one-to-many relation and User-to-Upvote has a one-to-many relation.
I want to do something similar to the upvoting done on Stackoverflow. So when you upvote/downvote the arrow will highlight and remain highlighted even if you refresh the page or come back to the page days/weeks later.
Currently I am doing this:
<% if Upvote.voted?(@user.id, comment.id) %> <%= link_to '^', ... style: 'color: orange;'%> <% else %> <%= link_to '^', ... style: 'color:black;'%> <% end %>
voted? method looks like this:
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 on a page, this will load an upvote from my database 10 times, just to check if it exist!
There has to be a better way to go about doing this, but I think my brain stopped working, so I can't think of any.