Removing constraints in migration
With a migration you can create a table or insert data to a table, also there is a possibility to modify existing tables; from renaming tables to changing the type of a column. And what about constraint such as default value or not null?
Yeah, you can change them too, but I was only successful with adding them — removing them was not possible with standard Rails methods.
I tried to create a migration that would remove the NOT NULL constraint from a column.
My first try was:
-
class ChangeCustomerColumns < ActiveRecord::Migration
-
def self.up
-
change_column :customers, :surname, :string
-
end
-
-
def self.down
-
change_column :customers, :surname, :string, :null => false
-
end
-
end
but nothing changed (PostgreSQL: to see the actual structure of a table type in the psql application with the \d table_name command).
Then I tried the following line, but also no difference.
-
change_column :customers, :surname, :string, :null => true
It seems that the only way how to do it is to call an SQL statement :(
I have a PostgreSQL database, so my migration is the following:
-
class ChangeCustomerColumns < ActiveRecord::Migration
-
def self.up
-
execute "alter table customers " +
-
"alter column surname drop not null;"
-
end
-
-
def self.down
-
execute "alter table customers " +
-
"alter column surname set not null;"
-
end
-
end
The same applies for the default value constraint: drop default or set default "John Smith".










