Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly hook into after_create in Rails model

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?


1 Answers

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.

like image 121
lucapette Avatar answered Oct 22 '25 03:10

lucapette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!