javascript 像 Ruby on Rails 中的按钮 Ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24221367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:23:27  来源:igfitidea点击:

Like button Ajax in Ruby on Rails

javascriptruby-on-railsrubyajaxsocial-media-like

提问by gd.silva

I have a Ruby on Rails project with a model Userand a model Content, among others. I wanted to make possible for a user to "like" a content, and I've done that with the acts_as_votablegem.

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

At the moment, the liking system is working but I'm refreshing the page every time the like button (link_to) is pressed.

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

I'd like to do this using Ajax, in order to update the button and the likes counter without the need to refresh the page.

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

In my Content -> Showview, this is what I have:

在我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>

The Contentcontroller does this to like/dislike:

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

And in my routes.rb file, this is what I have:

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

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

As I said, the liking system is working fine, but does not update the likes counter nor the like button after a user presses it. Instead, to trick that, I call redirect_to @contentin the controller action.

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

How could I implement this with a simple Ajax call? Is there another way to do it?

我怎么能用一个简单的 Ajax 调用来实现呢?还有另一种方法吗?

回答by DMKE

You can do so in various ways, the simple way goes like this:

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

Preparations

准备工作

  1. Include Rails UJS and jQuery in your application.js(if not already done so):

    //= require jquery
    //= require jquery_ujs
    
  2. Add remote: trueto your link_tohelpers:

    <%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>
    
  3. Let the controller answer with a non-redirect on AJAX requests:

    def like
      @content = Content.find(params[:id])
      @content.liked_by current_user
    
      if request.xhr?
        head :ok
      else
        redirect_to @content
      end
    end
    
  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
    

Advanced behaviour

高级行为

You probably want to update the "n users liked this" display. To archieve that, follow these steps:

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

  1. Add a handle to your counter value, so you can find it later with JS:

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

    Please also note the use of data-id, not id. If this snippet gets used often, I'd refactor it into a helper method.

  2. Let the controller answer with the count and not simply an "OK" (plus add some information to find the counter on the page; the keys are arbitrary):

    #…
    if request.xhr?
      render json: { count: @content.get_likes.size, id: params[:id] }
    else
    #…
    
  3. Build a JS (I'd prefer CoffeeScript) to react on the AJAX request:

    # 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
    

    Again, we're using the data-idattribute, to update only the affected counters.

  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属性仅更新受影响的计数器。

Toggle between states

在状态之间切换

To dynamically change the link from "like" to "dislike" and vice versa, you need these modifications:

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

  1. Modify your view:

    <% 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 %>
    

    Again: This should go into a helper method (e.g. vote_link current_user, @content).

  2. And your 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
    
  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