Rails模型中的条件验证

nul*_*tek 11 validation activerecord ruby-on-rails ruby-on-rails-3 rails-activerecord

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

在呼叫模型中有两个字段:location_id(与预定义位置列表的关联)和:location_other(可以是某人可以键入字符串的文本字段,或者在这种情况下是地址).

我希望能够做的是在创建对以下位置的调用时使用验证:location_id或:location_other被验证存在.

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

Joe*_*edy 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

替代解决方案

class Call < ActiveRecord::Base
  validates :location_id, presence: true, unless: :location_other
  validates :location_other, presence: true, unless: :location_id
end
Run Code Online (Sandbox Code Playgroud)

此解决方案(仅适用)如果存在location_idlocation_other是独占或.

有关更多信息,请查看Rails验证指南.