ruby-on-railsrubyacts-as-votable

Acts_As_Votable can't vote on other user's posts


I am using the acts_as_votable gem and am having an issue with the voting.

I have two models - User and Post. A User is able to vote on a post.

The problem I am having is that the User is only currently able to vote on their own post, but not other users' posts.

I think this is because I have done @posts.each and then the user is only being accessed for their own posts, so they can only vote on their own posts. Or the problem is in my index method in my controller.

Index.html.erb File:

<% @posts.each do |post| %>
    <div class="user-input">
        <% if post.user.voted_up_on? post %>
            <%= link_to unlike_post_path(post), method: :put do %>
                <%= image_tag("/assets/like.png") %>
            <% end %>
        <% else %>
            <%= link_to like_post_path(post), method: :put do %>
                <%= image_tag("/assets/heart.png") %>
            <% end %>
        <% end %>
    </div>
<% end %>

Posts_controller (relevant methods):

def index
    @posts = Post.includes(:user).order("created_at DESC") #Possible issue is here??
end

def like
    @post.upvote_by current_user
    redirect_to :back
end

def unlike
    @post.unvote_by current_user
    redirect_to :back
end

Routes:

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

If someone could help me understand why a User is only able to vote on their own posts that would be great.


Solution

  • Got it.

    Had to replace

    <% if post.user.voted_up_on? post %>
    

    with:

    <% if current_user.liked? post %>
    

    I believe it was asking if the creator of the post has voted on the post, whereas I needed just the current user to see if they have voted on the post.