简体   繁体   English

Rails验证和自定义回调顺序

[英]Rails validations and custom callbacks ordering

I have the below validations for one of my models. 我对以下其中一个模型进行了以下验证。 The goal is to validate presence of first_name, last_name, and shop. 目的是验证first_name,last_name和shop的存在。 Then after (but still before validation), I want to run my custom validation :status. 然后之后 (但仍验证之前),我要运行我的自定义验证:状态。

  validates_presence_of :first_name
  validates_presence_of :last_name
  validates_presence_of :shop

  validate :status, :on => :create

def status
  do stuff with first_name and last_name
end

But it appears that :status is running before the other validations, so I am getting errors for nil first_name etc. How can I correct this? 但是,似乎:status在其他验证之前运行,所以我在nil first_name等错误中遇到错误。如何解决此问题?

If you don't want your custom validation to run if the other validations have come back as invalid, do this: 如果您不希望您的自定义验证在其他验证返回为无效的情况下运行,请执行以下操作:

def status
  return if errors.present?
  do stuff with first_name and last_name
end

I will try to help. 我会尽力的。 If status is a field in your table, you have to change the custom validate name. 如果status是表中的字段,则必须更改自定义验证名称。 For instance 例如

validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :shop

validate :check_status, :on => :create

def check_status
  if first_name.present? && last_name.present? && shop.present?
    do stuff with first_name and last_name
    errors.add(:status, "you message here.") // if you need a error message
  end
end

For more information here custom validation . 有关更多信息,请参见自定义验证 Hopefully it can help you 希望它可以帮助您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM