Reputation: 2085
I want to make some styling changes if user has voted for a photo, and I used this code (acts_as_votable docs):
<% if current_user.voted_for? @photo %>
<%= link_to like_photo_path(@photo), method: :put do %>
<button>
¡Liked!
</button>
<% end %>
<% else %>
You dont like it yet
<% end %>
But this wont work because it will show "Liked" all the time, even if I didn't click the Like button.
photos controller
def upvote
@photo = Photo.friendly.find(params[:id])
@photo.liked_by current_user
redirect_to user_photo_path(@photo.user,@photo)
end
What can it be wrong?
Upvotes: 1
Views: 1300
Reputation: 3935
Add an additional condition in your if statement
<% if current_user.voted_for? @photo && @photo.liked_by current_user %>
# different text
<% elsif current_user.voted_for? @photo %>
<%= link_to like_photo_path(@photo), method: :put do %>
<button>
¡Liked!
</button>
<% end %>
<% else %>
You dont like it yet
<% end %>
This is a pretty common design pattern of basically falling through to the next logical default.
Note that if you find yourself nesting "if" statements, like so
if condition_one
if condition_two
if condition_three
# do something
else
# do something else
end
This is the same as
if condition_one && condition_two && condition_three
# do something
else
# do something else
end
If you find yourself falling into the nested ifs pattern then rethink what you're doing. You may need to decompose the code into a helper method, etc.
Upvotes: 3