Leo
Leo

Reputation: 2103

how exactly does rails callbacks work

I'm curious how exactly those callbacks work. If i initialize an object, and then use method save to throw it into my database, will before_create callback work? Similar thing with before_save. is it called literally only before function save is being used, or will it be triggered also in case of using create method?

Upvotes: 0

Views: 221

Answers (2)

Mischa
Mischa

Reputation: 43298

before_save will be triggered before you save a record. It doesn't matter whether you're creating or updating a record, your callback will be triggered. So, yes, it will also be triggered when you use the create method.

before_create is only triggered before creating a record, not before updating a record.

There is also before_update, which is only triggered before updating, but not before creating.

This doesn't depend on which method you use, it depends on whether the record was persisted before or not. In other words, it depends on whether you're updating or creating a record.

Upvotes: 2

Nitin
Nitin

Reputation: 7366

http://api.rubyonrails.org/v4.1.1/classes/ActiveRecord/Callbacks.html this url will help you find right answer for you. On this url you can also find the sequence for call back. Hope it helps you.

Upvotes: 0

Related Questions