Callbacks difference

What is the difference between before_create and before_save? Aren’t they both the same thing? If I want to set the column of the model what should I use?

When should one use after and before? Are they useful only during validations?

before_save will run whenever the record is saved while before_create only runs before creation. You want before_create if you want to only do something when you initially make the record while you need before_save if you want to do something whenever the record is created or edited.

Oh. So if I want to set a column value when the user is created for the time then I can use before_create? I don’t expect the user’s jabber_id to change because I create that when his account is created for the first time.

Exactly. However, if you want the jabber_id to always be calculated from an attribute, say the username, you’d use before_save.

So since in my case the username doesn’t change after the initial account creation so I should use before_create. And if the jabber_id changes on username change after the account creation then I should use before_save.

Technically, if you always expect jabber_id to be calculated from an attribute like username, you wouldn’t want to use a hook at all, you’d want to override either username=, or have jabber_id just be a plain old method.

@seangriffin agreed. That is a bad example. A better example of using before save is perhaps halting a save based on “locking” a model or something. e.g:

before_save :check_if_locked

def check_if_locked
  if locked
    errors.add(:base, "Can't change a locked record.")
    false
  end
end