I have a model:
class Reservation < ActiveRecord::Base
# amount_received :integer
# event_id :integer
# confirmed_at :datetime
belongs_to :event
I’d like to do something like:
`self.confirmed_at = Time.zone.now if amount_received >= event.price`
in the model whenever amount_received is changed (or I suppose whenever model is saved?). But not sure where to put this in a Rails app?
It sort of wants to be in the model because it is changing the state of the model BUT it depends on a value in a related model event.price and event means nothing in the model. Do I really want to query the DB for Event.find(event_id) in the model of another object?
Set me straight, thanks!
There are two easy options…
Me personally, since this model has a defined relation and needs to know about it, I’d put it in a pre save callback and be done with it. However if you are concerned with keeping one model independent of another, you could also place this in an observer. That way, you could have a separate object which merely observes the reservation and deals with the other relationship. I would personally not opt to go that route, however, since what you are updating is a property of the reservation model and I think it’s entirely reasonable that your reservation model be aware of the event and know how to respond to event properties.