2013-02-16 116 views
0

应用程序有Add to Cart按钮,它创建了新的@line_item(代码基于Agile Development with Rails)。 我添加了一个Ajax功能,所以Add to Cart不会重新加载页面,并添加@line_item to @cart按钮“添加”行为很奇怪

但是Rails每按一次按钮就会这样做三次!

我推“添加到购物车”,它增加了3项。

另外,当我emty车,它问我三次“你确定吗?” 不知道,有什么可能导致这些,有什么想法?

def create 
@cart = current_cart 
product = Product.find(params[:product_id]) 
@line_item = @cart.add_product(product.id) 
respond_to do |format| 
if @line_item.save 
format.html { redirect_to(store_url) } 
format.js 
format.xml { render :xml => @line_item, 
:status => :created, :location => @line_item } 
else 
format.html { render :action => "new" } 
format.xml { render :xml => @line_item.errors, 
:status => :unprocessable_entity } 
end 
end 
end 

按钮:

<%= button_to 'Add to Cart' , line_items_path(:product_id => product),:remote => true %> 

create.js.erb:

$('#cart').html("<%= escape_javascript(render(@cart)) %>"); 

_cart.html.erb模板:

<div class="cart_title" >Your Cart</div> 
<table> 
<%= render(cart.line_items) %> 
<tr class="total_line" > 
<td colspan="2" >Total</td> 
<td class="total_cell" ><%= number_to_currency(cart.total_price) %></td> 
</tr> 
</table> 
<%= button_to 'Empty cart' , cart, :method => :delete, 
:confirm => 'Are you sure?' %> 

_line_item.html.erb模板:

<tr> 
<td><%= line_item.quantity %>&times;</td> 
<td><%= line_item.product.title %></td> 
<td class="item_price" ><%= number_to_currency(line_item.total_price) %></td> 
</tr> 
+0

请向我们展示此按钮的代码以及页面的完整源代码。 – 2013-02-16 10:52:15

+0

编辑亩先发帖子与其他信息 – 2013-02-16 12:17:46

+0

它曾经发生过我,所有的事件都被解雇了两次。这是你的情况吗?如果是的话,那么可能是你的一些宝石/ javasript文件不止一次地添加jquery。 – 2013-02-16 14:02:58

回答

0

问题已解决。

在我看来,应用程序布局我认为这是正确的,不会做出这种

<!DOCTYPE html> 
<html> 
<head> 
    <title>Store</title> 
    <%= stylesheet_link_tag "store" %> 
    <%= javascript_include_tag 'application' %> 
    <%= csrf_meta_tags %> 
    <title>Cart</title> 
    <%= stylesheet_link_tag "carts" %> 
    <%= javascript_include_tag 'cart' %> #this 
    <%= csrf_meta_tags %> 

其实,我想一旦你使用主页上的“应用程序”,#这dublicates的JS代码执行