简体   繁体   中英

How To Fix undefined method `product' for #<LineItem::ActiveRecord_Relation:0x0000000017b22f70>

I'm try product quantity - 1 but ı get this error

line_item.rb

belongs_to :order
belongs_to :product

payment.rb

has_many :orders

undefined method `product' for # 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

If you use where , you don't get a single LineItem object, but a LineItem::ActiveRecord_Relation object. If that condition is enough to get just one record then use find_by . If it's not you need to think more about the logic because you'd get more than one object.

@line_item = LineItem.find_by(:order_id => params[:zc_orderid])

If you want to decrease the quantity of all those line items I'd do something like

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

LineItem.where(:order_id => params[:zc_orderid]) its return as array format.

So you can fetch by following LineItem.find_by(order_id: params[:zc_orderid]) . its return single active record

Since Order has many LineItem you should expect more than one line, so should rewrite your code:

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

Btw, consider add a Transaction .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM