I need to remove a few columns from my rails model which i already created and have some row entries in that model. How to do it? Any links which has details for modifying the schema in rails ? I'm using rails version 3.
Asked
Active
Viewed 5.5k times
3 Answers
62
To remove a database column, you have to generate a migration:
script/rails g migration RemoveColumns
Then in the self.up class method, remove your columns:
def self.up
remove_column :table_name, :column_name
end
You may want to add them back in the self.down class method as well:
def self.down
add_column :table_name, :column_name, :type
end
The Rails Guide for this goes into much more detail.

Tim
- 1,326
- 1
- 15
- 27

Jason stewart
- 1,085
- 8
- 8
-
3You don't have to specify `script/rails` with Rails 3. `rails g migration RemoveColumns` would suffice. – vonconrad Oct 16 '10 at 12:35
45
If you know the columns you want to remove you can use the convention: Remove..From.. when naming your migrations. Additionally you can include the column names when running the migration command.
The form of the command:
rails g migration Remove..From.. col1:type col2:type col3:type
For example:
rails g migration RemoveProjectIDFromProjects project_id:string
generates the following migration file:
class RemoveProjectIdFromProjects < ActiveRecord::Migration
def self.up
remove_column :projects, :project_id
end
def self.down
add_column :projects, :project_id, :string
end
end

Marcelo De Polli
- 28,123
- 4
- 37
- 47

slm
- 15,396
- 12
- 109
- 124
-
2Did this change in Rails 4? When I tried using your example it only generated a change method (no up/down methods). – Dan Jan 15 '14 at 21:19
-
@Dan - maybe. I haven't tried it in 4. 3 was the last time I tried this. I'll take a look later tonight and report back. – slm Jan 15 '14 at 21:25
-
3After a bit more research it looks like there is only supposed to be a change method in Rails 4. The remove_column now takes a data type which must be how it handles adding the column back. – Dan Jan 15 '14 at 21:31
-
@Dan - I should mention that this Q is approp. tagged as ruby-on-rails-3 for this, so a new Q&A might be warranted w/ a link to this Q&A just to keep things connected. – slm Jan 15 '14 at 21:34
-
1This SO Q&A seems to have more on the subject: http://stackoverflow.com/questions/2831059/how-to-drop-columns-using-rails-migration. Power's answer mentions the diffs in 3 vs. 4 with this method: http://stackoverflow.com/a/17792447/33204 – slm Jan 15 '14 at 21:38
10
Via command alternative as Add
, only change Add
to Remove
:
Single Column:
rails g migration RemoveColumnFromTable column:type
Multiple Columns:
rails g migration RemoveColumn1AndColumn2FromTable column1:type colummn2:type

leo.fcx
- 6,137
- 2
- 21
- 37

Gediminas Šukys
- 7,101
- 7
- 46
- 59