user1463822
user1463822

Reputation: 887

Rails: updating model triggers after_save callback "on: :create"

Rails 4.1.8.

So I have this thing:

class Post < ActiveRecord::Base
  after_save :weak, on: :create

  def weak
    puts "lamerino"
  end
end

Right?

So I fire rails console:

2.1.4 :008 > post = Post.create(name: "slow")
   (0.1ms)  begin transaction
   SQL (0.1ms)  INSERT INTO "posts"....
lamerino

post.name = "slow-mo"
post.save

2.1.4 :014 > post.save
   (0.1ms)  begin transaction
   SQL (0.2ms)  UPDATE "posts" SET ...
lamerino

As you can see "lamerino" was printed twice. For create and for update operations. Now, I only want this to be printed only for create operations. I thought that passing in on: :create will do that thing, but apparently it does not.

I ended up using after_create :weak.

I would like to know why updating record triggered the after_save :weak, on: :create callback.

Upvotes: 1

Views: 1696

Answers (1)

Arsen
Arsen

Reputation: 10951

It's because only validation callbacks accept on

https://github.com/rails/rails/issues/12502

Upvotes: 1

Related Questions