say i have a model
class Post < ActiveRecord::Base
validates_uniqueness_of :title, :unless => Proc.new {|p| p.deleted?}
end
The constraint is i can have only 1 post having "foobar" as its title while it's not deleted, and 1+ posts, which are all having deleted to be true, also having "foobar" as their titles. Since ActiveRecord can not guarantee the uniqueness of the title from this link, I'm trying to add a unique index to the table posts, on columns [:title, :deleted], it will fail the scenario when I try to insert a new deleted post to the db.
It's Possible in postgresql
add_index :table_name, :columns, unique: true, where: "(deleted_at IS NULL)"
It is not possible to have a conditional database index with most databases e.g. MySQL.
Probably the best option if you absolutely must guarantee uniqueness would be to have a separate table of deleted posts. You have the unique index on the main table, but not on the table containing deleted records. You would end up with a smaller posts table and simpler coding - there's no longer a need to filter out deleted posts in any queries.
Have you considered what should happen if you undelete a post - can two posts then have the same title?
Some other options are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With