SQL constraints through migrations

Hi,

I have to add contraints (CHECK) on a sql table through rails migration.
How should I? I googled and got to know about using something as
follows,

def self.up
execute “ALTER TABLE table_name ADD CONSTRAINT check_constraint_name
CHECK (check_column_name IN (1, 2, 3) )”
end

But am not sure if it appropriate to implement it this way or if there
is
any better method to get it done?

Regards,
Sumit

On Feb 25, 2013, at 5:17 AM, Sumit S. wrote:

Hi,

I have to add contraints (CHECK) on a sql table through rails migration. How
should I? I googled and got to know about using something as follows,

def self.up
execute “ALTER TABLE table_name ADD CONSTRAINT check_constraint_name CHECK
(check_column_name IN (1, 2, 3) )”
end

But am not sure if it appropriate to implement it this way or if there is any
better method to get it done?

I haven’t heard it mentioned in a while, but the foreigner gem was
popular here last year. You might want to look at that.

Walter

There is special gem that makes it possible.
See GitHub - vprokopchuk256/mv-core: Migration Validators project core classes for details.

With that gem you can do it in this way:

def up
change_table :table_name do
t.change :check_constraint_name, :integer, inclusion: { in: [1, 2,
3],
as: :check }
end
end

Best regards,
Valeriy Prokopchuk

понеділок, 25 лютого 2013 р. 12:17:28 UTC+2 користувач Sumit S.
написав:

I didn’t know that gem, I’ll take a look on that.

With Postgres, you can use this one
too: GitHub - take-five/postgresql-check: Adds helpers to migrations and dumps check constraints to schema.rb

Em sexta-feira, 23 de janeiro de 2015 18:33:37 UTC-2, Valera Prokopchuk
escreveu: