valibuk.net

A place for opinions and notes of a valibuk.

Removing constraints in migration

Tagged with: — ondrej at 7:44 pm on Wednesday, October 4, 2006

Ruby on RailsWith 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:

  1. class ChangeCustomerColumns < ActiveRecord::Migration
  2.   def self.up
  3.     change_column :customers, :surname, :string
  4.   end
  5.  
  6.   def self.down
  7.     change_column :customers, :surname, :string, :null => false
  8.   end
  9. 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.

  1. 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:

  1. class ChangeCustomerColumns < ActiveRecord::Migration
  2.   def self.up
  3.     execute "alter table customers " +
  4.       "alter column surname drop not null;"
  5.   end
  6.  
  7.   def self.down
  8.     execute "alter table customers " +
  9.       "alter column surname set not null;"
  10.   end
  11. end

The same applies for the default value constraint: drop default or set default "John Smith".

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • DZone
  • Digg
  • Reddit
  • Technorati
  • Furl
  • NewsVine
  • Slashdot
  • Ma.gnolia
  • StumbleUpon

2 Comments »

Comment by rc

April 18, 2008 @ 7:31 am

thx for help.
weird isn’t it.

Comment by ondrej

April 18, 2008 @ 8:46 am

you are welcome.
yes, it is weird…

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Preview


commercial break :)

Make an account on slicehost.com -- a really good hosting where you have your own virtual machine. I installed Gentoo there = I like it very much ;)