【问题标题】:Rails: Id validationRails:身份验证
【发布时间】:2018-04-15 17:26:53
【问题描述】:

我想为我的数据库创建一个验证。我有一张动物表,有 3 列:猫、狗、鱼。所有列默认为零。 所以,当创建一个新行时,我需要一个 id 到一列,其他必须为零。例如:

Dog: nil | Cat: 5 | Fish: nil | IS OKAY
Dog: 8 | Cat: nil | Fish: nil | IS OKAY
Dog: nil | Cat: 3 | Fish: 4 | WRONG, IMPOSSIBLE TO SAVE
Dog: 1 | Cat: nil | Fish: 9 | WRONG, IMPOSSIBLE TO SAVE

我必须做些什么来验证这一点?谢谢。

【问题讨论】:

    标签: sql ruby-on-rails ruby database model-view-controller


    【解决方案1】:

    您可以添加custom validation method:

    class Animal < ApplicationRecord
      validate :only_one_column_must_be_set
    
      def only_one_column_must_be_set
        if [dog, cat, fish].compact.count > 1
          errors.add(:base, "only one value must be set")
        end
      end
    end
    

    检查 compact 以从数组中排除 nil 值。

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 2016-04-12
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多