Rails 2.3.14: before_validation isn't run when saving without validation

There is an update of a field I wish to do when saving an object. This update must happen whether the object is validated or not, and must happen before validation.

The problem is that before_validation doesn't run when saving without validation. Where should this piece of code reside? is there a way to call the before_validation callback when saving without validating?

Thanks!

Answers


No, according to http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

You are hitting this problem because you are being naughty, you are saving without validation. Stop that. Seriously. Instead, you should relax your validation strategy so all this "saving without validation" nonsense, becomes "saving with validation" instead.

To do that, you can pass some options to validation methods, or have some conditional clauses in a custom validate methods.

class User < ActiveRecord::Base
  before_validation :my_crazy_thing      
  validates_presence_of :name, :unless => :is_a_robot?

  def is_a_robot?
    @brain_type == :positronic
  end

  def my_crazy_thing
    @brain_type = brain_surgery.brain_type
    # or whatever
  end

  def validate
    if condition_exists_to_run_custom_validations
      errors.add_to_base 'WTF' if @universe.exploded?
    end
  end
end

So where before, you would have had to skip validation so that robots could exist without a name. But if you setup validations properly, then you never need to save without them. You can tell you've set them up properly because you don't have to save without validating any more. And now you can properly use the before_validation callback all the time as a nice bonus.


Need Your Help

Spring i18n question marks instead of text

java spring localization internationalization

I hava i18n, but experience problems with russian letters. I have question marks ????? instead of text. Configuration: