How to remove a column from my Rails model?

Ruby on-RailsRuby on-Rails-3

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHemanthView Question on Stackoverflow
Solution 1 - Ruby on-RailsJason stewartView Answer on Stackoverflow
Solution 2 - Ruby on-RailsslmView Answer on Stackoverflow
Solution 3 - Ruby on-RailsGediminasView Answer on Stackoverflow