简体   繁体   English

Rails - 自定义唯一性验证

[英]Rails - Custom validation of uniqueness

I want to impart uniqueness on a column (type string), however the problem is on some of the strings I'm truncating part of the beginning before inserting them into the database using a function and before_save . 我想在列(类型字符串)上赋予唯一性,但是问题在于我在使用函数和before_save将它们插入数据库之前截断部分开头的一些字符串。 Thus the rails uniqueness validation doesn't work since the input might be different from what's in the database, even though after the truncation/formatting, they should be the same. 因此,rails唯一性验证不起作用,因为输入可能与数据库中的输入不同,即使在截断/格式化之后,它们应该是相同的。

I want to be able to truncate my string first, then validate it's uniqueness, however I'm not sure if it's possible using the rails validates uniqueness: true . 我希望能够先截断我的字符串,然后验证它的唯一性,但是我不确定是否可以使用rails validates uniqueness: true Will I just have to write a custom validate ? 我只需要编写自定义validate吗?

The order of Rails callback is: Rails回调的顺序是:

(-) save (-) 救

(-) valid ( - )有效

(1) before_validation (1)before_validation

(-) validate ( - )验证

(2) after_validation (2)after_validation

(3) before_save (3)before_save

(4) before_create (4)before_create

(-) create (-) 创造

(5) after_create (5)after_create

(6) after_save (6)after_save

(7) after_commit (7)after_commit

The detail is here . 细节在这里 So you just simply do something like: 所以你只需做一些像:

validates :your_data_field, uniqueness: true
before_validation :normalize_data

def normalize_data
  # Normalize your data here
end

So it will work exactly as you described, and don't need to write and custom validation. 因此它将完全按照您的描述工作,并且不需要编写和自定义验证。 It will be more beautiful! 它会更漂亮!

As you mentioned, you'll want to create a custom validator and use validates_with. 如您所述,您将需要创建自定义验证器并使用validates_with。 Information about that is here: 有关的信息在这里:

http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_with http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_with

To follow DRY principles, and also to ensure any changes to your truncation logic are reflected in both your validator and your before_save callback, I suggest creating a method that returns the truncated string, and use that same method within the validator and the callback. 要遵循DRY原则,并确保截断逻辑的任何更改都反映在验证器和before_save回调中,我建议创建一个返回截断字符串的方法,并在验证器和回调中使用相同的方法。

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

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