就像Ruby on Rails中的按钮Ajax一样
我有一个Ruby on Rails项目,其中包括模型User
和模型Content
等。 我希望用户能够“喜欢”一个内容,并且我已经使用acts_as_votable gem完成了这项工作。
目前,喜欢系统正在运行,但每次按下喜欢按钮(link_to)时我都会刷新页面。
我想使用Ajax来做这件事,以便更新按钮和喜欢的计数器,而无需刷新页面。
在我的Content -> Show
视图中,这就是我所拥有的:
· users like this
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调用实现它? 还有另一种方法吗?
您可以通过各种方式完成此操作,简单的方法如下:
准备工作
-
在你的
application.js
包含Rails UJS和jQuery(如果还没有这样做的话)://= require jquery //= require jquery_ujs
-
将
remote: true
添加到link_to
帮助程序:<%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>
-
让控制器回答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个用户喜欢这个”显示。 要实现这一点,请按照下列步骤操作:
-
为计数器值添加一个句柄,以便稍后使用JS找到它:
<%= @content.get_likes.size %> users like this
还请注意使用
data-id
,而不是id
。 如果经常使用这个片段,我会将其重构为辅助方法。 -
让控制器回答计数而不仅仅是“OK”(加上一些信息来找到页面上的计数器;键是任意的):
#… if request.xhr? render json: { count: @content.get_likes.size, id: params[:id] } else #…
-
构建一个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
属性来仅更新受影响的计数器。
在州之间切换
要动态地将链接从“喜欢”更改为“不喜欢”,反之亦然,您需要进行以下修改:
-
修改你的观点:
<% 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:
$(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