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

主宰稳场 提交于 2020-01-02 04:44:06

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/5356100/what-is-covered-by-savevalidate-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!