Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a check constraint in a Rails migration?

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?

like image 393
Jeff Avatar asked Jan 12 '11 01:01

Jeff


People also ask

How do I enable check constraints?

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.

Can you edit a migration file rails?

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.

How does rails check for pending migrations?

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."


2 Answers

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 
like image 97
Nilesh Avatar answered Sep 19 '22 02:09

Nilesh


Rails 6.1+ Check Constraints

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.

like image 28
Marian13 Avatar answered Sep 18 '22 02:09

Marian13