[英]Uniqueness in reverse validation for rails model
I have rails model with two attributes :ticket_id
and :parent_ticket_id
. 我有两个属性的铁路模型:ticket_id
和:parent_ticket_id
。 I want to validate such that there is only record having these two values. 我想验证是否只有记录具有这两个值。 For example, 例如,
There should be one and only record with 4 and 1 应该只有一个记录,其中包含4和1
:ticket_id => 4, :parent_ticket_id => 1
And I don't want any more rows having these same two values in any combination. 而且我不希望任何行都具有这两个相同值的任何组合。 Nothing of the sort (1,4) or (4,1). 没有(1,4)或(4,1)之类的东西。
will validates :ticket_id, :uniqueness => true, :scope => :parent_ticket_id
work? 将validates :ticket_id, :uniqueness => true, :scope => :parent_ticket_id
有效? I guess this will prevent just (1,4) combination and not (4,1).. 我猜这将防止(1,4)组合,而不会(4,1)。
You can do this in a custom validator (this query looks both ways in one query versus Salil using two different queries to do it): 您可以在自定义验证器中执行此操作(此查询在一个查询中与在Salil中使用两种不同的查询来完成两种方式都一样):
validate :ticket_and_parent_ticket_are_unique
private
def ticket_and_parent_ticket_are_unique
errors.add(:base, 'They are not unique') if ModelName.exists?(:ticket_id => [self.ticket_id, self.parent_ticket_id], :parent_ticket_id => [self.ticket_id, self.parent_ticket_id])
end
I don't think this is present in Rails, you have to write your own something like following 我认为这在Rails中不存在,您必须编写自己的类似下面的内容
validate :some_method_name
def some_method_name
if ModelName.exists?(:ticket_id => self.ticket_id, :parent_ticket_id => self.parent_ticket_id) || ModelName.exists?(:ticket_id => self.parent_ticket_id , :parent_ticket_id => self.ticket_id)
self.errors.add :base, '<Your ERROR Message Here>'
end
end
No Check though 虽然没有检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.