MechDog
MechDog

Reputation: 548

Rails model set boolean when record updated

I have model that I want to set a boolean to false whenever it is changed. Taht way I can reprocess it later to make sure the related records are up to date. I've tried a few things, but keep getting myself into a loop.

/app/model/contest.rb

class Contest < ActiveRecord::Base
  has_many :results, dependent: :destroy

  after_update :set_contest_not_updated

  def set_contest_not_updated
    self.contest_updated=false
    self.save
  end

  def set_contest_updated
    self.update_column(:contest_updated_at, Time.now)
    self.update_column(:contesy_updated, true)
  end

Expected action:

  contest.update_atrributes(flag_that_effects_scoring: true)

I would expect that is the above is run, the contest.contest_updated boolean would be set to false and only be set to true when the contest.set_contest_updated() method is run.

Upvotes: 1

Views: 563

Answers (2)

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

Of course calling save in the after_update callback will get you into a loop. It keeps saving over and over again until the end of time.

However, before_update should get the job done.
PS: Don't call save on *_save and *_update callbacks. This will always get you into loops.

  before_update :set_contest_not_updated

  def set_contest_not_updated
    self.contest_updated = false
  end

Upvotes: 2

ilan berci
ilan berci

Reputation: 3881

This will never work as when your after_update is called, it will invoke another after_update call and you will get the stack level too deep message.

The best solution is to have a foriegn key in another table/model such as contest_updates.

If you want your solution however, set the flag in a before_update filter

Upvotes: 0

Related Questions