Search code examples
ruby-on-railsrubyacts-as-votable

Acts_As_Votable Gem Automatically Liking Everything


I'm using the acts_as_votable gem to like and unlike "Deals" in my Ruby on Rails project. My user is set to act_as_voter and my deal is set to acts_as_votable, but for some reason everything is set to like as soon as a new user is created, and they can't unlike the deal. For some reason my list of deals all have an unlike button and it doesn't actually do anything but refresh the page. Here's some of my code.

app/views/catalog/index.html.erb

<ul class="deals_list">
  <% @deals.each do |deal| %>
    <li>
      <div>
        ...
      <div class="favorite">
        <% if account_signed_in? and current_account.accountable_type == "Personnel" %>
          <%= image_tag("dark-favorite.png") %>
          <% if deal.liked_by current_account %>
            <%= link_to unlike_deal_path(deal), method: :put do %>
              Unlike
            <% end %>
          <% else %>
            <%= link_to like_deal_path(deal), method: :put do %>
              Like
            <% end %>
          <% end %>
        <% end %>
      </div>
    </li>
  <% end %>
</ul>

app/controllers/deals_controller.rb

def like
    @deal = Deal.find(params[:id])
    @deal.liked_by current_account
    redirect_back(fallback_location: catalog_index_url)
  end

  def unlike
    @deal = Deal.find(params[:id])
    @deal.unliked_by current_account
    redirect_back(fallback_location: catalog_index_url)
  end

config/routes.rb

resources :deals do
    member do
      put 'like', to: "deals#like"
      put 'unlike', to: "deals#unlike"
    end
  end

Solution

  • Be sure and read the entire Readme because you're using the library wrong.

    To check if a voter has voted on a model, you can use voted_for?. You can check how the voter voted by using voted_as_when_voted_for.

    I zeroed in on your problem because I was expecting to see a "?" after the deal.liked_by call, which would indicate a boolean result (by convention, not always the case).

    So use this instead:

    <% if current_account.voted_for? deal %>