Ruby-on-rails 仅在创建和更新时验证 Rails 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1393698/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:43:39  来源:igfitidea点击:

Rails model validation on create and update only

ruby-on-railsvalidationmodel

提问by Jakub Arnold

If I want to have validation only on create, then I can do

如果我只想在创建时进行验证,那么我可以做

validates_presence_of :password, :on => :create

But how do I say on create and update? I tried this but it didn't work:

但是我怎么说创建和更新?我试过这个,但没有用:

validates_presence_of :password, :on => [ :create, :update ]

Do I have to define the validation two times?

我必须定义两次验证吗?

回答by Alessandra Pereyra

By default, the validations run for both create and update. So it should be just:

默认情况下,验证同时针对创建和更新运行。所以它应该只是:

validates_presence_of :password

The :on key just allows you to choose one of them.

:on 键只允许您选择其中之一。

回答by FJ.

Only write:

只写:

validates_presence_of :password

No need...

不需要...

on => :create

回答by Ederson Badeca

You can use this when you need to disable the validation on some specific operations, such as delete.

当您需要禁用某些特定操作(例如删除)的验证时,您可以使用它。