简体   繁体   English

Ruby On Rails validates_uniqueness_of具有范围和日期范围

[英]Ruby On Rails validates_uniqueness_of with scope and date range

Is it possible to use validates_uniqueness_of cars only in the case when car.created_at is > 6.months.ago? 仅当car.created_at> 6.months.ago时才可以使用validates_uniqueness_of汽车吗?

In my case, 就我而言

validates_uniqueness_of :car, :scope => [:dealer_id, :type], :on => :create

should allow to create a car for the same dealer_id and with the same type only if last created car with this data was created more then 6.months.ago 仅当最后一次使用此数据创建的汽车的创建时间超过6.months.ago时,才应允许使用相同的Dealer_id和相同的类型创建汽车。

You can probably do something like this. 您可能可以做这样的事情。

validate :be_a_new_car, :on=>:create

def be_a_new_car
 old_car = self.class.where(:car=>self.car,:dealer_id=>self.dealer_id,:type=>self.type)
           .where("created_at < ?",6.months.ago).first
 self.errors.add(:car, "not old enough to be unique") if old_car
end

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

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