Reputation: 35
I have Car
model, which is associated with many other models. How can I check updated_at of all associated models and get the latest of them, something like:
Car door was updated at "this time"
I have many associations in my model so getting each one of them and comparing is not efficient. If there is a better way please tell me. Thanks.
Upvotes: 0
Views: 514
Reputation: 1244
You could use the touch method here. Basically, touch is used to update the updated_at
field of a record. For example, Car.last.touch
would set the updated_at
field of the last Car
record to the current time.
However, touch
can also be used with relations, to trigger the touch
method on the associated object. So, in your case something like this may work:
class Car < ActiveRecord::Base
belongs_to :corporation, touch: true
end
class Door < ActiveRecord::Base
belongs_to :car, touch: true
end
# Door updation triggers updated_at of parent as well
@door = Door.last
@door.updated_at = DateTime.now
@door.save! # Updates updated_at of corresponding car record as well
In the example above, @door.touch
could also have been used to update the updated_at
of the corresponding parent Car
record.
Upvotes: 2