13

我有一个 Ruby on Rails 项目,其中包含一个模型User和一个模型Content等。我想让用户“喜欢”一个内容成为可能,我已经使用acts_as_votable gem 做到了这一点。

目前,点赞系统正在运行,但每次按下点赞按钮 (link_to) 时我都会刷新页面。

我想使用 Ajax 来执行此操作,以便在无需刷新页面的情况下更新按钮和点赞计数器。

在我Content -> Show看来,这就是我所拥有的:

<% if user_signed_in? %>
  <% if current_user.liked? @content %>
      <%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put %>
  <% else %>
      <%= link_to "Like", like_content_path(@content), class: 'vote', method: :put %>
  <% end %>
  <span> · </span>
<% end %>

<%= @content.get_likes.size %> users like this
<br>

控制器这样Content做是为了喜欢/不喜欢:

def like
    @content = Content.find(params[:id])
    @content.liked_by current_user
    redirect_to @content
end

def dislike
    @content = Content.find(params[:id])
    @content.disliked_by current_user
    redirect_to @content
end

在我的 routes.rb 文件中,这就是我所拥有的:

resources :contents do
    member do
        put "like", to: "contents#like"
        put "dislike", to: "contents#dislike"
    end
end

正如我所说,点赞系统运行良好,但在用户按下后不会更新点赞计数器或点赞按钮。相反,为了欺骗它,我调用redirect_to @content了控制器动作。

我如何通过简单的 Ajax 调用来实现这一点?还有另一种方法吗?

4

1 回答 1

31

您可以通过多种方式执行此操作,简单的方法如下:

准备工作

  1. application.js在您的(如果尚未这样做)中包含 Rails UJS 和 jQuery :

    //= require jquery
    //= require jquery_ujs
    
  2. 添加remote: true到您的link_to助手:

    <%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>
    
  3. 让控制器对 AJAX 请求进行非重定向回答:

    def like
      @content = Content.find(params[:id])
      @content.liked_by current_user
    
      if request.xhr?
        head :ok
      else
        redirect_to @content
      end
    end
    

高级行为

您可能想要更新“n 个用户喜欢这个”显示。要存档,请按照下列步骤操作:

  1. 为您的计数器值添加一个句柄,以便您稍后可以使用 JS 找到它:

    <span class="votes-count" data-id="<%= @content.id %>">
      <%= @content.get_likes.size %>
    </span>
    users like this
    

    还请注意使用data-id,不是id。如果这个片段经常被使用,我会将它重构为一个辅助方法。

  2. 让控制器回答计数,而不仅仅是“OK”(加上一些信息以在页面上找到计数器;键是任意的):

    #…
    if request.xhr?
      render json: { count: @content.get_likes.size, id: params[:id] }
    else
    #…
    
  3. 构建一个 JS(我更喜欢 CoffeeScript)来响应 AJAX 请求:

    # Rails creates this event, when the link_to(remote: true)
    # successfully executes
    $(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
      # the `data` parameter is the decoded JSON object
      $(".votes-count[data-id=#{data.id}]").text data.count
      return
    

    同样,我们使用该data-id属性仅更新受影响的计数器。

在状态之间切换

要将链接从“喜欢”动态更改为“不喜欢”,反之亦然,您需要进行以下修改:

  1. 修改您的视图:

    <% if current_user.liked? @content %>
      <%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: like_content_path(@content), id: @content.id } %>
    <% else %>
      <%= link_to "Like", like_content_path(@content), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: dislike_content_path(@content), id: @content.id } %>
    <% end %>
    

    再次:这应该进入一个辅助方法(例如vote_link current_user, @content)。

  2. 还有你的 CoffeeScript:

    $(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
      # update counter
      $(".votes-count[data-id=#{data.id}]").text data.count
    
      # toggle links
      $("a.vote[data-id=#{data.id}]").each ->
        $a = $(this)
        href = $a.attr 'href'
        text = $a.text()
        $a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
        $a.data('toggle-text', text).data 'toggle-href', href
        return
    
      return
    
于 2014-06-14T15:51:31.633 回答