Created
February 25, 2016 22:12
-
-
Save dtaniwaki/ad96f841313456f4ce1d to your computer and use it in GitHub Desktop.
Unique constraint with logical delete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LogicalDeleteUsers < ActiveRecord::Migration | |
def up | |
add_column :users, :logical_uniqueness, :boolean, default: true | |
remove_index :users, :name | |
add_index :users, [:name, :logical_uniqueness], unique: true | |
execute <<-SQL | |
CREATE TRIGGER `set_logical_uniqueness_on_users` BEFORE UPDATE ON `users` | |
FOR EACH ROW | |
BEGIN | |
IF NEW.`deleted_at` IS NULL THEN | |
SET NEW.`logical_uniqueness` = TRUE\; | |
ELSE | |
SET NEW.`logical_uniqueness` = NULL\; | |
END IF\; | |
END; | |
SQL | |
end | |
def down | |
execute <<-SQL | |
DROP TRIGGER `set_logical_uniqueness_on_users`; | |
SQL | |
remove_index :users, [:name, :logical_uniqueness] | |
add_index :users, :name, unique: true | |
remove_column :users, :logical_uniqueness | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment