简单的喜欢/不象按钮轨道3,jQuery和AJAX [英] Simple like/unlike button with rails 3, jquery, and ajax

查看:109
本文介绍了简单的喜欢/不象按钮轨道3,jQuery和AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产品,用户,和类似的模式。用户可以喜欢的产品。我想实现一个简单的像按钮,,在一点击,允许用户喜欢的产品。然后等按钮变换成一个不同于按钮,允许用户向产品不同。 pretty的简单。

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 the like button transforms into an unlike button, allowing the user to unlike a product. Pretty straightforward.

我已经实现了上述模型/控制器逻辑。我不是很好的JavaScript / AJAX,想知道什么是最好的办法是实现上述功能。我想类似/不同的行为由AJAX来处理。我使用的轨道3和jQuery UJS对我的应用程序。

I have implemented the model/controller logic for the above. I am not very good with javascript/ajax and was wondering what the best way would be to implement the above functionality. I want the like/unlike actions to be handled via ajax. I am using rails 3 and jquery ujs for my app.

感谢。

推荐答案

我的回答你的问题很长,所以我写了一个示例应用程序。这里有一个片段:

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

有很多方法对皮肤这只猫,但我喜欢渲染的部分和一个UJS模板。

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 ,其中#像是DIV封闭的形式:

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

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

这篇关于简单的喜欢/不象按钮轨道3,jQuery和AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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