Simple like/unlike button with rails 3, jquery, and ajax

烈酒焚心 提交于 2019-11-28 18:59:53

My answer to your question is long, so I wrote up an example application. Here's a snippet:

There are many ways to skin this cat, but I like to render a partial and a single ujs template.

_like_button.html.erb:

<% if like = current_user.likes.find_by_product_id(@product.id) %>
  <%= form_for like, :html => { :method => :delete },
                     :remote => true do |f| %>
    <%= f.submit "Unlike" %>
  <% end %>
<% else %>
  <%= form_for current_user.likes.build(:product_id => @product.id), :remote => true do |f| %>
    <%= f.hidden_field :product_id %>
    <%= f.hidden_field :user_id %>
    <%= f.submit "Like" %>
  <% end %>
<% end %>

toggle.js.erb, where "#like" is the div enclosing the form:

$("#like").html("<%= escape_javascript render('like_button') %>");

Basically, to make your links work via AJAX, you just need to provide link_to with :remote => true argument. But I guess you want to make some sort of feedback to the user. Take a look at this screencast.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!