Ruby on Rails Explained
before_save

Dec 15, 2018

ActiveRecord has a lot of callbacks but probably one of the most frequently used ones is before_save. There are a few other ones that are very similar like before_create and before_update, but they are just more narrowly scoped callbacks hat otherwise does the same thing.

As the name suggests, if you only need the callback to be run when a record is first created, use before_create. But if you need the callback to be invoked every time the record is updated instead, then you can use the before_update callback. And lastly if you need the callback to run when the object is both created and updated, you would use the before_save callback method.

Just like all other ActiveRecord public instance methods, you can access the instance within the invoked callback method simply by using the self reference. Calling the attribute methods directly also works since self is the default object in Ruby.

class Post < ApplicationRecord
  before_save :set_slug

  def set_slug
    self.slug = title.parameterize
  end
end

Post.create(title: "Foo bar")
=> #<Post id: 1, title: "Foo bar", slug: "foo-bar">