To calculate the total amount outside the `create_line_items` method, you can modify the `create_line_items` method to return the total amount and then use that value outside the method. Here's an example:

def create_line_items(items)
  total_amount = 0
  items.each do |data|
    sku = ProductSku.find(data[:sku_id])
    item = order_items.create!(
      amount: data[:amount].to_i,
      price: sku.price.to_i,
      product: sku.product,
      product_sku: sku
    )

    total_amount += sku.price.to_i * data[:amount].to_i

    sku.with_lock do
      sku.stock -= data[:amount].to_i
      sku.save
    end
  end

  total_amount
end

# Usage
items = [...]
total_amount = create_line_items(items)

In this example, the `create_line_items` method now returns the total amount, which can be assigned to a variable (`total_amount`) when calling the method.

Ruby on Rails: Calculate Total Amount in Order Model

原文地址: https://www.cveoy.top/t/topic/p9Ib 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录