Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: around_* callbacks

I have read the documentation at http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html, but don't understand when the around_* callbacks are triggered in relation to before_* and after_*.

Any help much appreciated.

Thanks.

like image 411
gjb Avatar asked Feb 14 '11 23:02

gjb


People also ask

What is around callback in rails?

In Rails, callbacks are hooks provided by Active Record that allow methods to run before or after a create, update, or destroy action occurs to an object. Since it can be hard to remember all of them and what they do, here is a quick reference for all current Rails 5 Active Record callbacks.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

Does Update_attributes call save?

Use update_attribute to skip validations. update_attribute uses save(false) while update_attributes uses save (which means save(true)). If perform_validation is false while calling save then it skips validation, and it also means that all the before_* callbacks associated with save.


2 Answers

around_* callbacks are invoked before the action, then when you want to invoke the action itself, you yield to it, then continue execution. That's why it's called around

The order goes like this: before, around, after.

So, a typical around_save would look like this:

def around_save    #do something...    yield #saves    #do something else... end 
like image 82
Jacob Relkin Avatar answered Oct 11 '22 15:10

Jacob Relkin


The around_* callback is called around the action and inside the before_* and after_* actions. For example:

class User   def before_save     puts 'before save'   end    def after_save     puts 'after_save'   end    def around_save     puts 'in around save'     yield # User saved     puts 'out around save'   end end  User.save   before save   in around save   out around save   after_save => true 
like image 34
Pan Thomakos Avatar answered Oct 11 '22 13:10

Pan Thomakos