6

I have an after_commit on: :create callback in my model, and it is being called twice. There are six methods in this callback, some of which are inserting into my database. I am afraid things are going to slow down AND my database is going to grow too quickly.

What's odd is that my before_create after_create callbacks are only executing once. What could be causing this?

Bholzer
  • 189
  • 1
  • 11

2 Answers2

6

Short answer: use after_save instead of after_commit

Long answer: How to organize complex callbacks in Rails?

Community
  • 1
  • 1
house9
  • 19,614
  • 8
  • 52
  • 60
  • 3
    Show us some code, are you calling save inside your callback? – house9 Aug 04 '12 at 03:29
  • 1
    No, I am not, should I be? `after_commit :func1, :func2, :func3, :func4, func5, :func6, on: :create` Despite it being on create, `model.save` seems to be triggering the callback. Is that normal? – Bholzer Aug 04 '12 at 03:41
  • @Bholzer are you sure the `on: :create` option is supported? I couldn't find the documentation for it (however the documentation is pretty bad, so I might be missing something). Instead I found `after_commit_on_create`, which might be what you should be using? – Casper Aug 04 '12 at 05:34
  • Yeah, it is supported. Extremely hard to find though, since like you said, the documentation is awful. Found [this post](http://stackoverflow.com/a/10356903/1566664) that shows its usage. The one you posted I believe requires a plugin. – Bholzer Aug 04 '12 at 16:24
0

I found using before_create solved the issue.

When you use the:

user = User.new
user.save

You are firing the before_save hook each time.

before_create

should work