Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before_validation, on: :save vs before_save

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?

like image 379
RobHeaton Avatar asked Nov 20 '25 17:11

RobHeaton


2 Answers

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/

like image 178
Yehuda Zargarov Avatar answered Nov 23 '25 06:11

Yehuda Zargarov


Since you are not actually validating anything, but manipulating an attribute, you should use a before_save callback.

Custom validation methods usually add an error to the model, and your set_name_from_email is not doing that.

like image 37
AlexBrand Avatar answered Nov 23 '25 06:11

AlexBrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!