我是rails的新手(第5周),目前我正在学习《敏捷web开发与rails 4》这本书。我刚刚完成了第11章,为了自娱自乐,我计划添加一个远程调用来销毁购物车中商品的所有数量。问题是,我得到一个内部错误信息500。
我在文件line_items/_line_item.html.erb中添加了代码"remote: true"
...
...
<%= button_to 'Remove Item', line_item, method: :delete, remote: true %>
并将html的重定向更改为store_path,并在line_items_controller.rb
中添加format.js我创建了一个destroy.js.erb文件,并添加了以下代码
$('#cartContainer').html('<%= escape_javascript render(@cart) %>');
我猜@cart是错误的。但我就是想不明白,可能我完全失去了对hole项目的概述:)
服务器日志:
Started DELETE "/line_items/105" for 127.0.0.1 at 2014-08-07 12:44:15 +0200
Processing by LineItemsController#destroy as JS
Parameters: {"authenticity_token"=>"ofobuV7Pk1avFiV6KSQ7NHnc/J77PJWWejsKVyg3YLQ=", "id"=>"105"}
LineItem Load (0.1ms) SELECT "line_items".* FROM "line_items" WHERE "line_items"."id" = ? LIMIT 1 [["id", 105]]
CACHE (0.0ms) SELECT "line_items".* FROM "line_items" WHERE "line_items"."id" = ? LIMIT 1 [["id", "105"]]
(0.1ms) begin transaction
SQL (0.4ms) DELETE FROM "line_items" WHERE "line_items"."id" = ? [["id", 105]]
(1.6ms) commit transaction
Rendered line_items/destroy.js.erb (0.9ms)
Completed 500 Internal Server Error in 8ms
ActionView::Template::Error ('nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.):
1: // reload cart after adding item
2: $('#cartContainer').html('<%= escape_javascript render(@cart) %>');
app/views/line_items/destroy.js.erb:2:in `_app_views_line_items_destroy_js_erb__1371414078062466935_70243559055940'
app/controllers/line_items_controller.rb:81:in `destroy'
你得到这个错误,因为@cart是nil。在你的控制器中destroy方法初始化@cart
def destroy
@cart = current_cart
// other logic
end