I need to add a new integer column to an existing table in my Rails app. The column can only have values 1, 2, 3, so I'd like to add a check constraint to the table/column. How do I specify this constraint within a Rails migration?
Enable a Check Constraint The syntax for enabling a check constraint in SQL Server (Transact-SQL) is: ALTER TABLE table_name WITH CHECK CHECK CONSTRAINT constraint_name; table_name. The name of the table that you wish to enable the check constraint.
If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.
If you need a bash one-liner to determine whether to run a migration or not (e.g., only migrate in a Heroku release phase command when there is a pending migration), this works: (rails db:migrate:status | grep "^\s*down") && rails db:migrate || echo "No pending migrations found."
Rails migration does not provide any way to add Constraints, but you can still do it via migration but by passing actual SQL to execute()
Create Migration file:
ruby script/generate Migration AddConstraint
Now, in the migration file:
class AddConstraint < ActiveRecord::Migration def self.up execute "ALTER TABLE table_name ADD CONSTRAINT check_constraint_name CHECK (check_column_name IN (1, 2, 3) )" end def self.down execute "ALTER TABLE table_name DROP CONSTRAINT check_constraint_name" end end
Rails 6.1 added basic support for check constraints to database migrations.
So now, a migration for adding a check constraint which restricts integer column values only to 1, 2, and 3 can be written as follows:
class AddConstraint < ActiveRecord::Migration def up add_check_constraint :table_name, 'check_column_name IN (1, 2, 3)', name: 'check_constraint_name' end def down remove_check_constraint :table_name, name: 'check_constraint_name' end end
Here is a link to the relative PR where you can find more details about add_check_constraint
and remove_check_constraint
.
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