P
P
Philipp2014-10-31 04:34:24
Ruby on Rails
Philipp, 2014-10-31 04:34:24

How to do calculations in the model?

There is an order model, it has a subordinate order position model.

class Order < ActiveRecord::Base
  has_many :order_items, :dependent => :destroy
  accepts_nested_attributes_for :order_items, :reject_if => lambda { |a| a[:inventory_id].blank? }, :allow_destroy => true
end

class OrderItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :inventory
  # в схеме есть свойство quantity - количество товара в строке заказа 
end

There is a model Goods in warehouses.
class Inventory < ActiveRecord::Base
  belongs_to :product
  belongs_to :stock
  # в схеме есть свойство amount - количество товара 
end

I don’t understand how to take goods from Inventory when ordering, change when adding, modify the quantity of goods in the order.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vsuhachev, 2014-10-31
@vsuhachev

inventory.update!(amount: inventory.amount - order_item.quantity)

A more specific decision depends on your product reservation process. One solution is to create a separate class that describes the reservation process
class OrderCheckoutService
  
  attr_accessor :order

  def initialize(order)
    @order = order
  end

  def checkout
    ActiveRecord::Base.transaction do
     # ваш код который переберет все позиции заказа, зарезервирует, сохранит, пошлет уведомления и т.п.
   end
  end

end

E
Eugene Burmakin, 2014-10-31
@Freika

You need to read about such a wonderful thing as transactions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question