Search code examples
ruby-on-railsnested-attributescocoon-gem

Access all associations, including nested attributes, before save model


I have an Order, an Item and a Product model.

class Order < ApplicationRecord
  has_many :items, dependent: :destroy, inverse_of: :order
end

class Item < ApplicationRecord
  belongs_to :order
  belongs_to :product
end

class Product < ApplicationRecord
  has_many :items
end

I need to calculate how many boxes every Item has (item.units/item.product.units_per_box), in a before_save callback, but I can't access the nested attributes, just the persisted items.

I've this in the Order model:

before_save :calculate_boxes, on: [:create, :update]

def calculate_boxes
  self.boxes = 0
  self.items.each do |item|
    self.boxes += item.units / item.product.units_per_box
  end
end

But, how I said, it just calculates the persisted items.

Don't know if it matters, but I am using @nathanvda's Cocoon gem to manage nested attributes on the create/edit form.


Solution

  • Try using self.items.collect. That should work. Also i would suggest you to use unless item.marked_for_destruction? inside the loop.