【问题标题】:Rails conditional validation in model模型中的 Rails 条件验证
【发布时间】:2014-08-29 17:43:57
【问题描述】:

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

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

我想要做的是在创建对 :location_id 或 :location_other 被验证存在的调用时使用验证。

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

【问题讨论】:

  • 我不太明白核心问题。是关于如何使用 valdates 宏的 if 和 unless 选项吗?还是关于如何在从某些控制器操作(而不是其他操作)保存模型时仅验证某些模型属性?
  • 很抱歉给您带来了困惑。我试图弄清楚在创建/保存记录时如何使用 if 和 unless 。最终目标是验证在创建/保存记录时是否设置了 :location_id 或 :location_other 。我只是不知道该怎么做。

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


【解决方案1】:

我相信这就是您要找的:

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 的存在是排他性的或,即两者只能存在一个,不能同时存在,也不能同时存在,那么您可以对@ 进行以下更改方法中的 987654329@ 块。

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 Validation Guide 了解更多信息。

【讨论】:

  • 感谢您的快速回复。第一个解决方案,创建自定义验证就可以了。我刚刚对自定义验证进行了一些研究并开始编写类似的东西,感谢您节省了我的时间并教了我。我很感激!
  • 没问题!并查看Rails Validation Guide(我也在我的更新答案中链接)以获取有关验证的更多信息。
  • 谢谢!这就是我一直在阅读的内容,并且在我开始写类似的东西时就开始了。但再次感谢您如此迅速地介入并提出一个简单的答案。非常感谢。
猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多