[英]How do you add a custom uniqueness validation to an ActiveRecord model in Rails?
I was perusing the Ruby on Rails Guides article on ActiveRecord validations and I came across this neat excerpt about the uniqueness
validation: 我仔细阅读了有关ActiveRecord验证的Ruby on Rails指南文章,并偶然发现了有关
uniqueness
验证的完整摘录:
There is also a :case_sensitive option that you can use to define whether the uniqueness constraint will be case sensitive or not.
还有一个:case_sensitive选项,可用于定义唯一性约束是否区分大小写。 This option defaults to true.
此选项默认为true。
This is a very useful feature to ensure that two users can't sign up with the same username or email, for example. 例如,这是一项非常有用的功能,可确保两个用户不能使用相同的用户名或电子邮件进行注册。 However, I want to use a similar validation but with a different method of determining the strings' equality.
但是,我想使用类似的验证方法,但是使用不同的方法来确定字符串的相等性。 I want to make sure that all of my entries are unique under
squeeze
. 我想确保所有输入在
squeeze
下都是唯一的。
As an example, say my Post
model has a text property content
. 例如,假设我的
Post
模型具有text属性content
。 I want to make sure that if foo bar
is already in the database, it will not accept foo bar
or foo bar
. 我想确保如果
foo bar
已经在数据库中,它将不接受foo bar
或foo bar
。 Is there a better way of doing this than just adding a custom validation to iterate over Post.all
, squeeze
ing each entry, and comparing it to the squeeze
d content
? 除了添加自定义验证以遍历
Post.all
, squeeze
每个条目并将其与squeeze
content
进行比较Post.all
,还有更好的方法吗? I can't imagine that scales well. 我无法想象这种缩放比例很好。
While you might try to accomplish everything in “Rails” way, in this particular case I would go another path. 尽管您可能尝试以“ Rails”方式完成所有任务,但在这种情况下,我会走另一条路。 If for some reason you want to keep
“foo bar”
content in the database, just introduce a new field squeezed_content
, implement a post_commit
hook to update this field with a squeezed value of content
and imply a validation on that newly introduced squeezed_content
field enforcing it to be unique. 如果出于某种原因要在数据库中保留
“foo bar”
内容,只需引入一个新字段squeezed_content
,实现一个post_commit
钩子即可使用content
的压缩值更新该字段,并暗示对新引入的squeezed_content
字段进行强制验证独一无二。
Also you might just store already squeezed values. 另外,您可能只存储已压缩的值。
You can add another column to your posts
table called squeezed_content
or something like that, then do something like this to use a built in uniqueness validation: 您可以将另一列称为
squeezed_content
或类似的内容添加到您的posts
表中,然后执行类似的操作以使用内置的唯一性验证:
class Post < ActiveRecord::Base
before_save :set_squeezed_content
validates :squeezed_content, uniqueness: true
def set_squeezed_content
self.squeezed_content = content.squeeze
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.