模型中的Rails条件验证 [英] Rails conditional validation in model

查看:53
本文介绍了模型中的Rails条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails 3.2.18应用程序,我正在其中尝试对模型进行条件验证。

I have a Rails 3.2.18 app where I'm trying to do some conditional validation on a model.

在调用模型中有两个字段:location_id (与预先定义的位置列表相关联)和:location_other(这是一个文本字段,用户可以在其中输入字符串或在这种情况下输入地址)。

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.

我已经阅读了Rails验证指南,有些困惑。希望有人可以有条件地阐明如何轻松地做到这一点。

I've read through the Rails validations guide and am a little confused. 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 是一种自定义验证方法,用于检查 location_id location_other 为空白。如果它们都是,那么它将添加一个验证错误。如果 location_id location_other 的存在是专有或,即,可以同时存在两个,而不是两者都存在,那么您可以对方法中的 if 块进行以下更改。

location_id_or_other is a custom validation method that checks if location_id and location_other are blank. If they both are, then it adds a validation error. If the presence of location_id and location_other is an exclusive or, i.e. 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.

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

替代解决方案

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

仅当存在 location_id location_other 是异或。

查看 Rails验证指南以获取更多信息。

这篇关于模型中的Rails条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆