before_validation, on: :save vs before_save

activerecord, ruby-on-rails

Solution

Normally I would place all data manipulating in the `before_save` since it is logical to have all data manipulations in one place (before saving).

However, if you would have validations on the name field in the future (even when the data manipulation does not affect validity) you should put your data manipulation in a `before_validation`, because you don't want storing data y in your db while validating data x.

You can read more about this here: http://bashar3a.com/2011/09/02/activerecord-callback-gotchas-before_save-vs-before_validate/

Problem

Say I have a model where I may need to manipulate some of its attributes before saving it: ``` class User < ActiveRecord::Base attr_accessible :name, :email # before_validation :set_name_from_email, on: :save # OR # before_save :set_name_from_email def set_name_from_email self.name ||= email end end ``` If I had to `validates :name, presence: true` then of course this would have to go in a `before_validation`. But if there is (as the code stands now) no chance of the callback affecting the validity of the object, is it better to put it in `before_save`? It seems neater to have all your data manipulating callbacks in either one or the other bucket, in case the code changes and the callback now COULD affect validity, but then again it seems bad to run callbacks unnecessarily when calling things like `.valid?`. Any strong opinions either way?

Original source