[英]Custom Uniqueness validator for hstore Postgres
I would like to perform a uniqueness validation on a hstore field. 我想对hstore字段执行唯一性验证。
When I set is as: 当我设置为:
class User
store_accessor :attributes, :foo_attr
validates :foo_attr, uniqueness: true
end
I get undefined method 'limit' for nil:NilClass
我得到undefined method 'limit' for nil:NilClass
In a Rails issue store_accessor and uniqueness validation? 在Rails问题中store_accessor和唯一性验证? user al2o3cr explains: 用户al2o3cr解释:
validates_uniqueness_of is not going to work in this case - it's expecting a database column named stripe_id. validates_uniqueness_of在这种情况下将不起作用-它期望一个名为stripe_id的数据库列。 With an Hstore column it's technically possible to perform the required query, but the resulting SQL is only applicable to that storage format and only works on Postgres. 使用Hstore列在技术上可以执行所需的查询,但是生成的SQL仅适用于该存储格式,并且仅适用于Postgres。
In your case, a custom subclass of ActiveRecord::Validations::UniquenessValidator with an overridden build_relation would probably be a better choice. 在您的情况下,具有覆盖build_relation的ActiveRecord :: Validations :: UniquenessValidator的自定义子类可能是一个更好的选择。
How would you go around creating that custom validator? 您将如何创建该自定义验证器?
I already have a database level uniqueness set up as explained in Race condition using Postgres hstore all I need now is to make valid? 我已经按照种族条件使用Postgres hstore设置了数据库级别的唯一性,现在我需要做的就是使它有效吗? return false on the same foo_attr. 在同一个foo_attr上返回false。
If you're going to the trouble of setting up a custom hstore index and writing a custom validation, my first instinct is that maybe you want foo_attr
to be a column of its own. 如果您要设置自定义hstore索引并编写自定义验证的麻烦,那么我的第一个直觉是,也许您希望foo_attr
成为其自己的列。
As for a custom validation, it's pretty straightforward: 至于自定义验证,这非常简单:
validate :foo_attr_uniqueness
def foo_attr_uniqueness
if self.class.where(foo_attr: foo_attr) # Same foo_attr
.where.not(id: id) # On a different record
.exists?
errors.add(:foo_attr, 'must be unique')
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.