How to remove a column from my Rails model?

I need to remove some columns from my rail model that I already created, and some rows in this model. How to do it? Any links that contain details for changing the circuit in rails? I am using rails version 3.

+47
ruby-on-rails ruby-on-rails-3
Oct. 16 2018-10-16
source share
3 answers

To remove a database column, you must create a migration:

script/rails g migration RemoveColumns 

Then, in the class method self.up, remove the columns:

 def self.up remove_column :table_name, :column_name end 

You can also add them back to the self.down class method:

 def self.down add_column :table_name, :column_name, :type end 

Rails Guide for this in more detail.

+51
Oct 16 2018-10-16
source share

If you know the columns that you want to remove, you can use the convention: Remove..From .. when naming your migrations. In addition, you can include column names when running the migration command.

Team Form:

 rails g migration Remove..From.. col1:type col2:type col3:type 

For example:

 rails g migration RemoveProjectIDFromProjects project_id:string 

creates 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 
+40
Aug 26 '11 at 18:40
source share

Alternatively, using the Add command, change only Add to Remove :

Single column:

 rails g migration RemoveColumnFromTable column:type 

Multiple Columns:

 rails g migration RemoveColumn1AndColumn2FromTable column1:type colummn2:type 
+1
Feb 05 '14 at 5:30
source share



All Articles