Let have Order and Item models.
class Order < ApplicationRecord
has_many :items, inverse_of: :order, dependent: :delete_all
before_save do
self.packed_volume = compute_packed_volume
end
private
def compute_packed_volume
items.count * 0.1O
end
end
And
class Item < ApplicationRecord
belongs_to :order, inverse_of: :items
end
The problem is that items.count is equals to 0 since items are not yet created. How can we get the number of items that will be created to used it when we create an order?
Try size
instead, it won't run a query
items.size * 0.1O
Hope that helps!