【问题标题】:Rails: How do I validate uniqueness of certain types in an enumRails:如何验证枚举中某些类型的唯一性
【发布时间】:2016-08-05 07:11:44
【问题描述】:

我有一个具有以下枚举的模型:

# Schema
# account_type :integer, not null

enum account_type: {
  user: 1,
  deposit: 2,
  withdrawal: 3,
  fee: 4
}

我必须确保只有一个 :deposit:withdrawal:fee 帐户存在,但允许无限数量的 :user 帐户。我该如何处理这个模型验证?

【问题讨论】:

    标签: ruby-on-rails activerecord enums


    【解决方案1】:

    您可以将条件传递给唯一性验证

    validates :account_type, uniqueness: true, if: '!account_type.user?'
    

    【讨论】:

    • 简短而甜蜜,但这不起作用,在条件中添加? 会引发语法错误。将答案的条件更改为'account_type == "user"',我会接受。
    【解决方案2】:
    validates :account_type, uniqueness: true, if: 'account_type == "user"'
    

    答案是基于@neydroid 的回答,虽然这本身是不正确的,而且他没有回应我的修复请求。

    【讨论】:

      【解决方案3】:
      class MyModel < ActiveRecord::Base
      
        validate :only_one_of_most_account_types
      
        def only_one_of_most_account_types
          return if account_type == 1
          match = MyModel.find_by(account_type: account_type)
          errors.add(:account_type, "Already have one of these") if match && match.id != id
        end
      
      end
      

      【讨论】:

        【解决方案4】:

        在您的情况下,account_typeenum,您可以直接使用提供的帮助程序 user?

        validates :account_type, uniqueness: true, if: :user?
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-25
          • 2020-08-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多