Rails模型中的条件validation

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

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

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

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

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

 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是一种自定义validation方法,用于检查location_idlocation_other是否为空。 如果它们都是,那么它会添加validation错误。 如果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的存在是异或,则此解决方案(仅)有效。

有关更多信息,请查看Railsvalidation指南 。