4

I currently have something like this:

class Article

  # fields = [flag, something]

  after_create :update_flag

  def update_flag
    self.flag = 1 if something_changed?
  end
end

But it doesn't change the 'flag' field when I change the something field. I've saved the object. Still no changes.

a = Article.create(flag: 0, something: "content")
a.something = "different"
a.save

a.flag
> 0

Any ideas?

Damien Roche
  • 13,189
  • 18
  • 68
  • 96

3 Answers3

7

Change

after_create

to

after_update

In your code example you're updating the object and that's the reason why you need a different hook. Please see docs for further information.

Josien
  • 13,079
  • 5
  • 36
  • 53
lucapette
  • 20,564
  • 6
  • 65
  • 59
  • Thank you very much, that worked. I was confused because I thought after_create hook was run whenever an object was initialized. I see I need to learn my hooks. Thanks again. – Damien Roche Jul 14 '12 at 10:40
0
after_create()

Is called after Base.save on new objects that haven‘t been saved yet (no record exists).

after_save()

Is called after Base.save (regardless of whether it‘s a create or update save).`

Amit Mutreja
  • 168
  • 1
  • 7
0

Change "after_create" to "after_save" because after_create only works once - just after the record is first created & after_save works every time you save the object - even if you're just updating it many years later.

Reference- What is the difference between `after_create` and `after_save` and when to use which?

Community
  • 1
  • 1
Piyush Chaudhary
  • 183
  • 2
  • 12