首页 > 解决方案 > 如何修复未定义的方法“产品”#

问题描述

我正在尝试产品数量 - 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

标签: ruby-on-railsrubyruby-on-rails-5

解决方案


如果你使用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

推荐阅读