ruby-on-rails - 如何修复未定义的方法“产品”#
问题描述
我正在尝试产品数量 - 1 但我收到此错误
line_item.rb
belongs_to :order
belongs_to :product
付款.rb
has_many :orders
# LineItem::ActiveRecord_Relation:0x0000000017b22f70> 的未定义方法“产品”
@line_item = LineItem.where(:order_id => params[:zc_orderid])
@line_item.product.quantity = @line_item.product.quantity - 1
if @line_item.product.quantity == 0
@line_item.product.sold = true
end
@line_item.product.save
解决方案
如果你使用where
,你不会得到一个LineItem
对象,而是一个LineItem::ActiveRecord_Relation
对象。如果该条件足以仅获得一条记录,则使用find_by
. 如果不是,您需要更多地考虑逻辑,因为您会得到不止一个对象。
@line_item = LineItem.find_by(:order_id => params[:zc_orderid])
如果你想减少所有这些订单项的数量,我会做类似的事情
LineItem.transaction do
LineItem.where(:order_id => params[:zc_orderid]).each do |line_item|
line_item.product.quantity = line_item.product.quantity - 1
if line_item.product.quantity == 0
line_item.product.sold = true
end
line_item.product.save
end
end
推荐阅读
- sql-server - SQL Server 比较小数点后的数字
- javascript - 如何根据按钮的值在一个按钮中调用两个函数而不是同一次单击?
- redis - 如何在redis中导出/导入带有模式的键?
- git - 我需要说明“git add a file”的完整路径吗
- java - Gradle 任务 assembleDebug 失败,退出代码为 1(运行时异常)
- ios - BOOL 在objective-c 中为0 值返回YES?
- git - GitFlow:有没有办法让我的本地主/开发分支与远程分支自动保持同步?
- javascript - 使用 JQuery 和 PHP 进行电话字段验证
- python - ValueError:无法使用 groupy 从重复轴重新索引并在 Pandas 中应用 pct_change
- c++ - 如何扩展此 Makefile 以使用通配符?