简体   繁体   English

Rails模型中的条件验证

[英]Rails conditional validation in model

I have a Rails 3.2.18 app where I'm trying to do some conditional validation on a model. 我有一个Rails 3.2.18应用程序,我正在尝试对模型进行一些条件验证。

In the call model there are two fields :location_id (which is an association to a list of pre-defined locations) and :location_other (which is a text field where someone could type in a string or in this case an address). 在呼叫模型中有两个字段:location_id(与预定义位置列表的关联)和:location_other(可以是某人可以键入字符串的文本字段,或者在这种情况下是地址)。

What I want to be able to do is use validations when creating a call to where either the :location_id or :location_other is validated to be present. 我希望能够做的是在创建对以下位置的调用时使用验证:location_id或:location_other被验证存在。

I've read through the Rails validations guide and am a little confused. 我已经阅读了Rails验证指南并且有点困惑。 Was hoping someone could shed some light on how to do this easily with a conditional. 希望有人可以通过条件轻松地阐明如何轻松地做到这一点。

I believe this is what you're looking for: 我相信这就是你要找的东西:

class Call < ActiveRecord::Base
  validate :location_id_or_other

  def location_id_or_other
    if location_id.blank? && location_other.blank?
      errors.add(:location_other, 'needs to be present if location_id is not present')
    end
  end
end

location_id_or_other is a custom validation method that checks if location_id and location_other are blank. location_id_or_other是一种自定义验证方法,用于检查location_idlocation_other是否为空。 If they both are, then it adds a validation error. 如果它们都是,那么它会添加验证错误。 If the presence of location_id and location_other is an exclusive or , ie only one of the two can be present, not either, and not both, then you can make the following change to the if block in the method. 如果location_idlocation_other的存在是异或或者两者中只有一个可以存在,而不是两者中的一个,而不是两者,那么您可以对方法中的if块进行以下更改。

if location_id.blank? == location_other.blank?
  errors.add(:location_other, "must be present if location_id isn't, but can't be present if location_id is")
end

Alternate Solution 替代解决方案

class Call < ActiveRecord::Base
  validates :location_id, presence: true, unless: :location_other
  validates :location_other, presence: true, unless: :location_id
end

This solution (only) works if the presence of location_id and location_other is an exclusive or. 如果location_idlocation_other的存在是异或,则此解决方案(仅)可用。

Check out the Rails Validation Guide for more information. 有关更多信息,请查看Rails验证指南

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

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