1

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?

Gibson
  • 2,055
  • 2
  • 23
  • 48
  • Can you show also the controller code for which this html is used? – Esse Nov 10 '14 at 18:22
  • Also: you don't want to use `button` inside `a` tag. More info: http://stackoverflow.com/questions/6393827/can-i-nest-a-button-element-inside-an-a-using-html5 – Esse Nov 10 '14 at 18:37

1 Answers1

3

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.

engineerDave
  • 3,887
  • 26
  • 28
  • Hi, I have the same issue and when I tried your solution i got undefined method voted_for? error? If i removed the voted_for, again all the posts automatically voted up. :-( – Learner Nov 26 '14 at 20:33