2013-02-16 105 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代碼執行