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.
我有一个Ruby on Rails项目,其中包括一个模型用户和一个模型内容。我想让用户能够“喜欢”一个内容,我已经用acts_as_votable gem完成了。
At the moment, the liking system is working but I'm refreshing the page every time the like button (link_to) is pressed.
目前,“喜欢”系统正在工作,但每次按下like按钮(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实现这一点,以便更新按钮和like计数器,而无需刷新页面。
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
And in my routes.rb file, this is what I have:
在我的路线。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 @content
in the controller action.
正如我所说的,喜欢系统运行良好,但是用户按下之后不会更新喜欢计数器或喜欢按钮。相反,为了技巧,我在控制器操作中调用redirect_to @content。
How could I implement this with a simple Ajax call? Is there another way to do it?
我如何通过一个简单的Ajax调用来实现这一点呢?还有别的办法吗?
1 个解决方案
#1
28
You can do so in various ways, the simple way goes like this:
你可以用不同的方式去做,简单的方法是这样的:
Preparations
-
Include Rails UJS and jQuery in your
application.js
(if not already done so):在应用程序中包含Rails UJS和jQuery。js(如果还没有的话):
//= require jquery //= require jquery_ujs
-
Add
remote: true
to yourlink_to
helpers:添加remote: true to your link_to helper:
<%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>
-
Let the controller answer with a non-redirect on AJAX requests:
让控制器对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个用户喜欢这个”的显示。按照以下步骤来归档:
-
Add a handle to your counter value, so you can find it later with JS:
添加一个句柄到您的计数器值,以便稍后您可以找到它与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
, notid
. If this snippet gets used often, I'd refactor it into a helper method.请注意数据id的使用,而不是id。
-
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):
让控制器回答计数,而不是简单的“OK”(加上添加一些信息以找到页面上的计数器;钥匙是任意的):
#… if request.xhr? render json: { count: @content.get_likes.size, id: params[:id] } else #…
-
Build a JS (I'd prefer CoffeeScript) to react on the AJAX request:
构建一个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
Again, we're using the
data-id
attribute, to update only the affected counters.同样,我们使用data-id属性只更新受影响的计数器。
Toggle between states
To dynamically change the link from "like" to "dislike" and vice versa, you need these modifications:
要动态地将链接从“喜欢”改为“不喜欢”,反之亦然,您需要这些修改:
-
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
).同样:这应该进入一个helper方法(例如vote_link current_user, @content)。
-
And your CoffeeScript:
和你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
28
You can do so in various ways, the simple way goes like this:
你可以用不同的方式去做,简单的方法是这样的:
Preparations
-
Include Rails UJS and jQuery in your
application.js
(if not already done so):在应用程序中包含Rails UJS和jQuery。js(如果还没有的话):
//= require jquery //= require jquery_ujs
-
Add
remote: true
to yourlink_to
helpers:添加remote: true to your link_to helper:
<%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>
-
Let the controller answer with a non-redirect on AJAX requests:
让控制器对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个用户喜欢这个”的显示。按照以下步骤来归档:
-
Add a handle to your counter value, so you can find it later with JS:
添加一个句柄到您的计数器值,以便稍后您可以找到它与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
, notid
. If this snippet gets used often, I'd refactor it into a helper method.请注意数据id的使用,而不是id。
-
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):
让控制器回答计数,而不是简单的“OK”(加上添加一些信息以找到页面上的计数器;钥匙是任意的):
#… if request.xhr? render json: { count: @content.get_likes.size, id: params[:id] } else #…
-
Build a JS (I'd prefer CoffeeScript) to react on the AJAX request:
构建一个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
Again, we're using the
data-id
attribute, to update only the affected counters.同样,我们使用data-id属性只更新受影响的计数器。
Toggle between states
To dynamically change the link from "like" to "dislike" and vice versa, you need these modifications:
要动态地将链接从“喜欢”改为“不喜欢”,反之亦然,您需要这些修改:
-
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
).同样:这应该进入一个helper方法(例如vote_link current_user, @content)。
-
And your CoffeeScript:
和你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