Difference between save(false) and save(:validate

2020-06-30 21:45发布

问题:

What's the difference between save(false) and save(:validate => false)? From what I can tell, the functionality is the same. The version that uses :validate is in the api which leads me to believe save(false) is a deprecated version? This came up for me when following this: https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user. The guide has save(false) in there but I was getting errors when using it. I switched it to the :validate version and that worked fine.

回答1:

In Rails versions before than 3, save was a method in ActiveRecord::Base and you could pass false to it in order to bypass validations.

In Rails 3, save was moved to ActiveRecord::Persistance and since then you should pass :validate => false to save in order to bypass validations.



回答2:

All the validation from model are skipped when we use validate: false

@user = User.new(....)

@user.save(validate: false)

Action base disable validation

http://www.dan-manges.com/blog/action-dependent-validations-and-why-on-update-is-bad

Skip Field validation

https://richonrails.com/articles/skipping-validations-in-ruby-on-rails

Example

class User < ActiveRecord::Base

validates_presence_of :password, :on => :update

end