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

2

6

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?

Hayfork answered 18/3, 2011 at 18:9 Comment(0)
T
3

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
Townsville answered 18/3, 2011 at 18:20 Comment(2)
how do you pass in :validate => false? I tried <%= form_for(@blob) :validate => false do |f| %> and it broke everything. I'm a bit of a newbie...Reticulation
@Michael that's in the update/create method of your controller... @model.save(:validate=>false)Townsville
S
4

Testing on Rails 4.2.6 shows that .save(:validate=>false) will actually skip before_validations and after_validation callbacks.

Sob answered 17/1, 2017 at 6:53 Comment(0)
T
3

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
Townsville answered 18/3, 2011 at 18:20 Comment(2)
how do you pass in :validate => false? I tried <%= form_for(@blob) :validate => false do |f| %> and it broke everything. I'm a bit of a newbie...Reticulation
@Michael that's in the update/create method of your controller... @model.save(:validate=>false)Townsville

© 2022 - 2024 — McMap. All rights reserved.