1

我正在用著名的书“Aglie web development with rails(4th editon)”来研究rails。在我完成示例“添加一点 Ajax”之后,我遇到了麻烦。我已将“create.js.rjs”更改为 create.js.rjs,其代码为:

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

之后,当我单击“添加到购物车”按钮时,购物车显示两个相同的产品。html 代码在这里:

<tr>
  <td>1×</td>
  <td>CoffeeScript</td>
  <td class="item_price">$36.00</td>
</tr>      
<tr>
  <td>1×</td>
  <td>CoffeeScript</td>
  <td class="item_price">$36.00</td>
</tr>
  <tr class="total_line">
  <td colspan="2">Total</td>
  <td class="total_cell">$72.00</td>
</tr>

在我重新加载页面后,它是正确的,只显示一项。

日志:

 Started POST "/line_items?product_id=10" for 127.0.0.1 at 2013-02-02 21:48:41 +0800
 Processing by LineItemsController#create as JS
 Parameters: {"authenticity_token"=>"K89hdtwnYs8TiSqYlYXVtWv1DixGPM8a4TnmDbudRqc=",  "product_id"=>"10"}
 Cart Load (0.2ms)  SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1  [["id", 40]]
 Product Load (0.2ms)  SELECT "products".* FROM "products" WHERE "products"."id" = ? ORDER BY title LIMIT 1  [["id", "10"]]
 LineItem Load (0.4ms)  SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = 40 AND "line_items"."product_id" = 10 LIMIT 1(0.1ms)  begin transaction
 SQL (0.6ms)  INSERT INTO "line_items" ("cart_id", "created_at", "product_id", "quantity", "updated_at") VALUES (?, ?, ?, ?, ?)  [["cart_id", 40], ["created_at", Sat, 02   Feb 2013 13:48:41 UTC +00:00], ["product_id", 10], ["quantity", 1], ["updated_at", Sat, 02 Feb 2013 13:48:41 UTC +00:00]](166.5ms)  commit transaction(0.2ms)  begin transaction(0.2ms)  commit transaction
 LineItem Load (0.6ms)  SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = 40
 Product Load (0.3ms)  SELECT "products".* FROM "products" WHERE "products"."id" = 10 ORDER BY title LIMIT 1
 Rendered line_items/_line_item.html.erb (4.4ms)
 Rendered carts/_cart.html.erb (11.7ms)
 Rendered line_items/create.js.erb (14.1ms)
 Completed 200 OK in 199ms (Views: 18.6ms | ActiveRecord: 169.2ms)



  Started GET "/" for 127.0.0.1 at 2013-02-02 21:50:58 +0800
  Processing by StoreController#index as HTML
  Product Load (0.4ms)  SELECT "products".* FROM "products" ORDER BY title
  Cart Load (0.2ms)  SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1  [["id", 40]]
  Rendered store/index.html.erb within layouts/application (4.9ms)
  LineItem Load (0.4ms)  SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = 40
  Product Load (0.5ms)  SELECT "products".* FROM "products" WHERE "products"."id" = 10 ORDER BY title LIMIT 1
  Rendered line_items/_line_item.html.erb (3.0ms)
  Rendered carts/_cart.html.erb (7.3ms)
  Completed 200 OK in 29ms (Views: 25.3ms | ActiveRecord: 1.4ms)

非常感谢您的帮助!

4

0 回答 0