So I have a pretty simple upvote system in my rails app, that allows users to upvote a pin:
pins_controller.rb
def upvote
@pin = Pin.friendly.find(params[:id])
if @pin.votes.create(user_id: current_user.id)
flash[:notice] = "Thanks for your recommendation."
redirect_to(pin_path)
else
redirect_to(pin_path)
end
end
And in my view they can upvote by clicking on a button (represented by an icon): in app/views/pins/index.html.erb
<%= link_to upvote_pin_path(pin), method: :post do %>
<span class="text-decoration: none;"><i class="fa fa-chevron-up"></i>
<% end %>
<%= pluralize(pin.votes.count, "") %></span>
I would like to render the icon in different color if the user has already upvoted the pins: So I thought about using exists?:
<%= link_to upvote_pin_path(pin), method: :post do %>
<% if pin.votes.where(user_id: current_user.id).exists? %>
<i class="fa fa-chevron-up" style="color:red"></i>
<% else %>
<i class="fa fa-chevron-up"></i>
<% end %>
<% end %>
But is doesn't work, instead all icons appears red, any ideas?
The problem is that you are checking whether the table exists (check the exists? documents).
What you want to do is check if it is empty?