Rails: updating an association
- by Sam
I have a Reservation model which belongs_to a Sharedorder and so a Sharedorder has_many reservations.
Give you a little background.
I sharedorder has many reservations and each reservation can have an amount. A sharedorder has three status: 1) reserved, 2) confirmed, 3) and purchased.
Here is my problem. When a reservation gets added to a sharedorder or an existing reservation's amount is updated I need this to affect the associated sharedoder because the status listed latter should only change when 100% of the reservations have been placed and so on.
Here are the things I have tried:
.
class Reservation < ActiveRecord::Base
before_save :sharedorder_reserved_status
def sharedorder_reserved_status
if self.sharedorder.reserved_percent(reservations_to_be_added) >= 100 && !self.sharedorder.reserved
self.sharedorder.update_attribute(:reserved, true)
self.sharedorder.update_attribute(:reserved_at, Time.now)
end
end
def reservations_to_be_added
if self.new_record?
self.amount
elsif self.amount_changed?
self.amount - self.amount_was
else
0
end
end
end
And then in the Sharedorder model:
class Sharedorder < ActiveRecord::Base
def reserved_percent(amount_change)
(((reserved_sum + amount_change).to_f / self.product.twenty_hq_size.to_f)*100).to_i
end
def reserved_sum
if !@reserved_sum
reserved_sum = 0
reserved_reservations.collect {|x| reserved_sum += x.amount }
reserved_sum
else
@reserved_sum
end
end
def reserved_reservations
@reserved_reservations ||= Reservation.find(:all, :conditions => ['canceled = ? AND sharedorder_id = ?', false, self.id ])
end
end
I have also tried :touch => true on the reservation model to update the sharedorder put for some reason it doesn't seem to include the latest reservation being added or being updated.
So what I'm trying to do is update the status of the sharedorder if a certain percent is reached and I have to send the additional amounts the the sharedorder for it to know to include additional reservations or updates on existing ones.
How should I do this?