ruby-on-railsruby-on-rails-3counter-cache

What is covered by save(:validate => false)?


I just implemented a number of custom counter_caches using code like this:

def after_save
    self.update_counter_cache
end
def after_destroy
    self.update_counter_cache
end
def update_counter_cache
    self.company.new_matchings_count = Matching.where(:read => false).count
    self.company.save
end

My question is this - what does the command Model.save(:validate => false) actually prevent beyond things like validates_with or before_validation?

Will my custom counter_caches be affected if I keep my existing saves without validation?


Solution

  • If you pass in the :validate=>false, it skips the valid? command. Everything else functions the same.

    You can check the code out here: http://api.rubyonrails.org/classes/ActiveRecord/Validations.html

    def save(options={})
      perform_validations(options) ? super : false
    end
    
    ...
    
    if perform_validation
      valid?(options.is_a?(Hash) ? options[:context] : nil)
    else
      true
    end