Refactor Steps
Examine each table. Are there any non-primary key columns that have a unique constraint, or which should have a unique constraint?
If you found places where you must add a unique constraint, add it:
create unique index concurrently
table_name_column_one_column_two_uniq_idx on table_name(column_one,column_two, ...);Choose the next steps based on whether your unique constraint is based on one column or multiple columns.
Single Column Refactor
In the table’s model class, change the primary key column using
set_primary_key:set_primary_key
:unique_columnIn tables that reference this table, add a column to reference the new key:
alter table
dependent_tableadd columnreferenced_table_unique_column coltype;Fill the column with appropriate values:
update
dependent_tablefromreferenced_tabler setreferenced_table_unique_column= r.unique_colwherereferenced_table_id = r.id;Add the foreign key reference constraint to each dependent table:
alter table
dependent_tableadd constraintreferenced_table_unique_column_fkey (referenced_table_unique_col) referencesreferenced_table(unique_col);Drop the original id column and reference:
alter table
referenced_tabledrop column id; alter tabledependent_tabledrop columnreferenced_table_id;Set the new column as the primary key:
alter table
referenced_tableadd primary key(unique_column);
Multiple Column Refactor
Install the
composite_primary_keysgem:gem install composite_primary_keys
Load the gem in your application. In environment.rb, add ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access