Rails模型中的条件验证

时间:2014-07-08 20:28:01

标签: ruby-on-rails ruby-on-rails-3 validation activerecord rails-activerecord

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

在呼叫模型中有两个字段:location_id(与预定义位置列表的关联)和:location_other(有人可以键入字符串或在本例中为地址的文本字段)

我希望能够做的是在创建对以下位置的调用时使用验证:location_id或:location_other已经过验证。

我已经阅读了Rails验证指南并且有点困惑。希望有人可以通过条件轻松地阐明如何轻松完成这项工作。

1 个答案:

答案 0 :(得分:19)

我相信这就是你要找的东西:

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_idlocation_other是否为空。如果它们都是,那么它会添加验证错误。如果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

替代解决方案

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

如果location_idlocation_other的存在是独占的,则此解决方案(仅适用)有效。

查看Rails Validation Guide了解详情。

相关问题