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

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 https://github.com/vprokopchuk256/mv-core 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 Srivastava написав:

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

With Postgres, you can use this one too: https://github.com/take-five/postgresql-check