Like按钮阿贾克斯的Ruby on Rails [英] Like button Ajax in Ruby on Rails

查看:197
本文介绍了Like按钮阿贾克斯的Ruby on Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Ruby on Rails项目与模型用户和模型内容,等等。我想使可能的用户喜欢的内容,并且我已经做了与 acts_as_votable 宝石。

I have a Ruby on Rails project with a model User and 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_votable gem.

目前,该喜好系统的工作,但我每次都像按钮(的link_to)刷新页面是pressed。

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

我想做到这一点使用Ajax,以便更新按钮和喜欢,而无需刷新页面反击。

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.

在我的内容 - >展看来,这就是我:

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

<% 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 Content controller does this to like/dislike:

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中的文件,这就是我的:

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

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

正如我说的,喜欢的系统工作正常,但不会更新喜欢的计数器,也不在用户presses它类似按钮。相反,欺骗,我称之为 redirect_to时@content 控制器动作。

我怎么能实现这一点的,简单的Ajax调用?是否有另一种方式做到这一点?

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

推荐答案

您可以通过多种方式做的话,简单的办法是这样的:

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

包括UJS的Rails和jQuery在你的的application.js (如果不这样做的话):

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

//= require jquery
//= require jquery_ujs

  • 添加远程:真正的的link_to 助手:

  • Add remote: true to your link_to helpers:

    <%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>
    

  • 让与控制器的答案非重定向AJAX请求:

  • 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
    

  • 您可能需要更新N个用户喜欢这个显示。要archieve的,请按照下列步骤操作:

    Advanced behaviour

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

    1. 添加一个句柄到你的计数器的值,这样你就可以用JS后发现:

    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
    

    另外,请注意使用数据的编号,,不是 ID 。如果这个片段被经常使用,我会重构它变成一个辅助方法。

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

    让与计数控制器的答案,而不是简单的OK(加添加一些信息来找到网页上的计数器;键是任意):

    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
    #…
    

  • 建立一个JS(我preFER的CoffeeScript)对AJAX请求作出反应:

  • 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
    

    此外,我们使用了数据ID 属性,仅更新受影响的计数器。

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

    要动态地改变从喜欢到不喜欢,反之亦然的链接,你需要这些修改:

    Toggle between states

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

    1. 修改您的看法:

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

    还是那句话:这应该进入一个辅助方法(例如: vote_link CURRENT_USER,@content

    和你的CoffeeScript:

    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
    

  • 这篇关于Like按钮阿贾克斯的Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆