class StudentItemOrder < ApplicationRecord
  include Base::StudentItemOrder
  associations_for legacy: true do |a|
    a.belongs_to :classroom, keys: :ClassID, optional: true
    a.belongs_to :family
    a.belongs_to :lunch_day
    a.belongs_to :school
    a.belongs_to :school_year
    a.belongs_to :student
    a.belongs_to :lunch_cycle, optional: true
    a.belongs_to :cafeteria_transaction, keys: :LTID, class_name: 'StudentCafeteriaTransaction',
      inverse_of: :student_item_order, optional: true
    a.belongs_to :lunch_price_plan, keys: :LPPID, optional: true
  end

  after_initialize :set_association_defaults

  scope :by_lunch_date, ->(date) { merge(LunchDay.by_date(date)) }

  private
    def set_association_defaults
      self.school = student.school if school_id.zero?
      self.family = student.family if family_id.zero?
      self.lunch_price_plan_id = 0 if lunch_price_plan_id.nil?
    end
end
