简体   繁体   English

Rails - 枚举不区分大小写

[英]Rails - Enumerize case insensitive

In a model I have in a Rails project, one field is used with Enumerize as follows:在我的 Rails 项目中的 model 中,一个字段与 Enumerize 一起使用,如下所示:

enumerize :status, in: %i[draft active], default: :active

If I used "active" as input it works, "ACTIVE" however gives an inclusion error.如果我使用“active”作为输入,它会起作用,但是“ACTIVE”会给出一个包含错误。

I tried to get around this by registering a before_validation callback我试图通过注册一个 before_validation 回调来解决这个问题

before_validation :downcase_fields

def downcase_fields
  status.downcase! if status.present?
end

but this doesn't work as well.但这也行不通。

How can I make an enumerizable field case insensitive in Rails?如何在 Rails 中使可枚举字段不区分大小写?

Your code looks fine, You can check on console by adding debugger in downcase_fields methos.您的代码看起来不错,您可以通过在 downcase_fields 方法中添加调试器来检查控制台。 Or you can simply add the validation check: uniqueness: {case_sensitive: false}或者您可以简单地添加验证检查:uniqueness: {case_sensitive: false}

Enumerize doesn't allow setting any value that is not one of the original acceptable set. Enumerize 不允许设置任何不是原始可接受集合之一的值。 For example if this is how the field is set in the model例如,如果这是在 model 中设置字段的方式

enumerize :status, in: %i[draft active], default: :active

trying status =:Active would not even set the field.尝试status =:Active甚至不会设置该字段。

The only I could do it, was through the setter (when the value is being set)我唯一能做的就是通过设置器(设置值时)

  def status=(value)
    super(value&.downcase)
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM