Ruby-on-rails Rails - 仅在创建时验证

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

Rails - Validate on Create Only

ruby-on-rails

提问by oprogfrogo

I'm trying to get my custom validation to work on create. But when I do a findthen save, rails treats it as createand runs the custom validation. How do I get the validations to only work when creating a new record on not on the update of a found record?

我正在尝试让我的自定义验证在create. 但是当我执行findthen 时save,rails 将其视为create并运行自定义验证。如何使验证仅在创建新记录时才起作用,而不是在更新已找到的记录时起作用?

回答by Tonys

Try this on your line of validation code:

在您的验证代码行上试试这个:

validate :custom_validation, :on => :create

this specifies to only run the validation on the createaction. Here's the link to the apidocs

这指定仅对操作运行验证create。这是apidocs的链接

回答by Matt

TL;DR; Full example:

TL; 博士; 完整示例:

class MyPerson < ActiveRecord::Base
  validate :age_requirement


  private

  def age_requirement
    unless self.age > 21 
      errors.add(:age, "must be at least 10 characters in length")
    end
  end

end

To have the validator run only if a new object is being created, you can change the 2nd line of the example to: validate :age_requirement, on: :create

要仅在创建新对象时运行验证器,您可以将示例的第二行更改为: validate :age_requirement, on: :create

Only on updates: validate :age_requirement, on: :update

仅在更新: validate :age_requirement, on: :update

Hope that helps the next person!

希望对下一个人有所帮助!