Can I have an table index that uses the current date as a condition?

24 Views Asked by At

As an example, let us say I have a table Coupons that has a the fields code, expiration_date, and status. A coupon instance can be archived based off its status or expiration_date. If it's status == "archived" OR if the current date is past the coupon's expiration_date. I want to create a unique index for the Coupons table where no two "active" coupons can have the same code. So in the migration file I would want to write something like this:

    add_index :coupons, %i[code], where: ('status <> 2 AND (expiration_date IS NULL OR expiration_date <= ?)', Time.now.utc), unique: true, name: 'index_unique_coupon_code'

I can not find the proper way to write this where condition to use the current date when validating for uniqueness in this example.

0

There are 0 best solutions below