所有帖子在登录后自动获得

时间:2016-03-16 20:44:24

标签: ruby-on-rails ruby-on-rails-4

我在这里有一些非常奇怪的情况。当我登录用户时,该用户会喜欢所有帖子。这是我的路线:

  resources :posts do
    member do
      put 'upvote', to: 'posts#upvote'
      put 'unvote', to: 'posts#unvote'
    end
  end

以下是观点:

  <% if logged_in? %>
    <% if post.liked_by current_user %>
      <%= link_to "Dislike", unvote_post_path(post), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: upvote_post_path(post), id: post.id } %>
    <% else %>
      <%= link_to "Like", upvote_post_path(post), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: unvote_post_path(post), id: post.id } %>
    <% end %>
  <% end %>

这是控制器:

  def upvote
    @post = Post.find(params[:id])
    @post.liked_by current_user
    if request.xhr?
      render json: { count: @post.get_likes.size, id: params[:id] }
    else
      redirect_to @post
    end
  end

  def unvote
    @post = Post.find(params[:id])
    @post.unliked_by current_user
    if request.xhr?
      render json: { count: @post.get_likes.size, id: params[:id] }
    else
      redirect_to @post
    end
  end

我使用了gem https://github.com/ryanto/acts_as_votable并在此之后添加了一些ajax交互:Like button Ajax in Ruby on Rails

1 个答案:

答案 0 :(得分:0)

问题在于if语句<% if post.liked_by current_user %>,它使用户喜欢这些帖子而不是布尔方法。我用<% if current_user.voted_for? post %>切换它并将acts_as_voter添加到用户模型,它现在运行正常。