よく知られている本「Agliewebdevelopmentwith rails(4thedition)」でレールを研究しています。そして、「Ajaxのダッシュを追加する」という例を実行した後、問題が発生します。「create.js.rjs」を「create.js.rjs」に変更しました。そのコードは次のとおりです。
$('#cart').html("<%= j render @cart %>");
その後、[カートに追加]ボタンをクリックすると、カートに2つの同じ製品が表示されます。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>
そして、ページをリロードした後、それは正しいです、1つのアイテムだけを表示します。
ログ:
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)
ご助力ありがとうございます!