Fellow Stranger
Fellow Stranger

Reputation: 34103

If a certain attribute is updated to true, then run method that updates another attribute

The claass User has the attributes activated: boolean and activated_at: date_time.

When the attribute activated gets set to the value true I want to automatically run a method that runs a couple of conditionals and then sets the attribute activated_at to the current date and time.

I tried to set an after_update :set_activated_at, if: :activated_changed? callback that updates activated_at if activated equals to true, but that of course creates an eternal loop.

What would be the best way to run a method to update an attribute if another attribute equals to a certain value?

Upvotes: 0

Views: 93

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52367

You were close, really!

after_update :set_activated_at

def set_activated_at
  if activated_changed? && activated == true
  update_column(:activated_at, Time.now)
end

Upvotes: 1

Related Questions