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

后端 未结 2 2016
梦毁少年i
梦毁少年i 2020-12-13 22:52

I have a product, user, and like model. A user can like a product. I am trying to implement a simple like button which, upon a click, allows a user to like a product. Then t

2条回答
  •  误落风尘
    2020-12-13 23:12

    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') %>");
    

提交回复
热议问题