我正在关注使用 Rails 5.1 进行敏捷 Web 开发这本书,并在第 11 章中尝试创建一个按钮来减少购物车中商品的数量。我正在尝试使用ajax来解决这个问题并在购物车上调用render方法。我收到以下错误...
ActionView::Template::Error ('nil' 不是一个与 ActiveModel 兼容的对象。它必须实现 :to_partial_path。): 1:cart = document.getElementById("cart") 2:cart.innerHTML = "<%= j渲染(@cart)%>”
如果更改了任何内容,则此 ajax 调用源自的按钮是部分按钮。我是 Rails 的新手并且被卡住了。
decrement_quantity.js.coffee
cart = document.getElementById("cart")
cart.innerHTML = "<%= j render(@cart) %>"
_line_item.html.erb
<% if line_item== @current_item %>
<tr class="line-item-highlight">
<% else %>
<tr>
<% end %>
<td id="quantity"><%= line_item.quantity %></td>
<td><%= line_item.product.title %></td>
<td id="price" class="price"><%= number_to_currency(line_item.total_price) %></td>
<td><%= button_to 'X', line_item, method: :delete, data: {confirm: 'Are you sure?' } %></td>
<td id="decrement_quantity"><%= button_to '-1', line_items_decrement_quantity_path(id: line_item.id), remote: true%></td>
</tr>
line_items_controller.rb
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create]
before_action :set_line_item, only: [:show, :edit, :update, :destroy, :decrement_quantity]
.
.
.
def decrement_quantity
if @line_item.quantity > 1
@line_item.quantity -= 1
@line_item.save
else
@line_item.destroy
end
respond_to do |format|
format.html { redirect_to store_index_url, notice: 'Line item was successfully decremented.' }
format.js {}
format.json { head :no_content }
end
end
.
.
.
路由数据库
Rails.application.routes.draw do
resources :line_items
resources :carts
#get 'store/index'
root 'store#index', as: 'store_index'
post 'line_items/decrement_quantity'
resources :products
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
我不确定我是否遗漏了什么,但是来自不同视图中不同按钮的相同 ajax 命令工作正常。任何帮助指导我的人都非常感谢:)
您尚未设置@cart
,这意味着您的视图正在执行"<%= j render(nil) %>"
。
您的控制器仅@cart
通过 before-action 设置,它只在create
操作之前运行:
before_action :set_cart, only: [:create]
如果您希望decrement_quantity
将@cart
变量推送到视图,您需要扩展only:
选项以包含[:create, :decrement_quantity]
(这可能有效也可能无效,您尚未在问题中包含该方法的内容)或@cart
在decrement_quantity
操作中显式设置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句