如何为#修复未定义的方法`product'

问题描述 投票:1回答:3

我正在尝试产品数量 - 1但是我得到这个错误

line_item.rb

belongs_to :order
belongs_to :product

payment.rb

has_many :orders

#LineItem :: ActiveRecord_Relation:0x0000000017b22f70>的未定义方法`product'

@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-rails ruby ruby-on-rails-5
3个回答
0
投票

由于Order有很多LineItem,你应该期望不止一行,所以应该重写你的代码:

LineItem.where(:order_id => params[:zc_orderid]).each do |line_item|
  product = line_item.product
  product.quantity -= 1
  if product.quantity == 0
    product.sold = true
  end
  product.save
end

顺便说一句,考虑添加一个Transaction


3
投票

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

0
投票

LineItem.where(:order_id => params[:zc_orderid])以数组格式返回。

所以你可以通过跟随LineItem.find_by(order_id: params[:zc_orderid])获取。它返回单个活动记录

© www.soinside.com 2019 - 2024. All rights reserved.