Sam 山
Sam 山

Reputation: 42865

Rails: How to perform callbacks on a model that is not updated but is related to updated model

to KIS I have two models: Reservations and Containers.

 Container 
 has_many :reservations

 Reservation
 belongs_to :container

When I update a reservation I also want to perform call backs on the respective Container.

What is a good way to do this?

Should I be using nested rest routes, put the container logic in the Reservation model, or something else

Upvotes: 0

Views: 522

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

Rails has an option called touch.

class Reservation < ActiveRecord::Base
  belongs_to :container, :touch => true
end

Rails updates the updated_at field of the Container object when ever Reservation object changes. If you have any callbacks in Container class they will be invoked when Reservation object changes.

class Container < ActiveRecord::Base
  has_many :reservations
  after_update :reservation_change

  def reservation_change
    # handle the updates..
  end
end

Upvotes: 1

Related Questions