Ruby-on-rails save(false) 和 save(:validate => false) 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8485002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between save(false) and save(:validate => false)
提问by Steve
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 :validateis 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 :validateversion and that worked fine.
save(false)和 和有save(:validate => false)什么区别?据我所知,功能是相同的。使用的版本:validate在 api 中,这让我相信save(false)是一个已弃用的版本?在遵循以下内容时,我想到了这一点:https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user。该指南save(false)在那里,但我在使用它时遇到错误。我将其切换到该:validate版本,效果很好。
回答by Behrang Saeedzadeh
In Rails versions before than 3, savewas a methodin ActiveRecord::Baseand you could pass falseto it in order to bypass validations.
在3比之前的Rails版本,save是一个法中ActiveRecord::Base,你可以通过false它才能绕过验证。
In Rails 3, savewas movedto ActiveRecord::Persistanceand since then you should pass :validate => falseto savein order to bypass validations.
在Rails 3,save被感动到ActiveRecord::Persistance,从那时起,你应该传递:validate => false到save以绕过验证。
回答by Jigar Bhatt
All the validation from model are skipped when we use validate: false
当我们使用时,将跳过模型的所有验证 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
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
https://richonrails.com/articles/skiping-validations-in-ruby-on-rails
Example
例子
class User < ActiveRecord::Base
类用户 < ActiveRecord::Base
validates_presence_of :password, :on => :update
validates_presence_of :password, :on => :update
end
结尾

