I just ran
script/generate migration add_type_to_users
in my terminal and it automatically generated a migration with the code generated for me.
1
2
3
4
5
6
7
8
9
class AddTypeToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :type, :type, :null => :no?, :default => :maybe?
  end

  def self.down
    remove_column :users, :type
  end
end

Am I being n00b, or is this a new feature in edge rails? Does this work for columns not reserved for rails?

UPDATE:

On further inspection, this is a new thing in edge rails and it does work for other columns. While running the following:

script/generate migration add_name_to_users
I got the following migration:
1
2
3
4
5
6
7
8
9
class AddNameToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :name, :type, :null => :no?, :default => :maybe?
  end

  def self.down
    remove_column :users, :name
  end
end
For a bit more experimentation I tried:
script/generate migration add_name_string_to_users
1
2
3
4
5
6
7
8
9
class AddNameStringToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :name_string, :type, :null => :no?, :default => :maybe?
  end

  def self.down
    remove_column :users, :name_string
  end
end
Unfortunately it seems you cannot specify type. I also tried to see if you could do multiple columns by trying:
script/generate migration add_name_and_date_to_users
and got the following:
class AddNameAndDateToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :name_and_date, :type, :null => :no?, :default => :maybe?
  end

  def self.down
    remove_column :users, :name_and_date
  end
end

It seems that the implementation is pretty primitive. Obviously I'm using a bad approach as I should be looking at the source to see if any additional implementation does exist without my knowing, but I was hoping that the most intuitive thing for me would implemented already. I think it would be cool to see this syntactic sugar get more advanced. Comments? Opinions?

NOTE: The code that is generated by the migration does not work automatically. You have to change the stubbed symbols placed inside the migration to whatever you need. It's more of a guide than a performance enhancer (which IMO think that it should be both).

1 Response to “Adding type to a table in migrations”

  1. Lonny Eachus Says:
    These examples should be changed. Intermittent problems have been reported with using "from", "type", and "name" as column names, although it is not documented that these are reserved. Until this problems is resolved, those should not be used as db column names in Rails.

Sorry, comments are closed for this article.