Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing multiple columns in table within a database. (rails)

I am having trouble removing multiple columns in my local database.

My table name is 'customers' and within that table the two columns I am trying to remove are 'phone' and 'fax'

I've been trying something along the lines of this

class CustomerCleanup < ActiveRecord::Migration
  def change_table(:customers) do |t|
      t.remove :fax, :phone
    end
  end
end

but I continue to get a syntax error stating 'unexpected tSYMBEG expecting ')'

I've looked at the examples in Here....and I've tried this as well only to get the same error

class CustomerCleanup < ActiveRecord::Migration
  def change_table(:customers) do |t|
      t.remove :fax
      t.remove :phone
    end
  end
end

Would anyone know what i'm doing wrong here?

like image 323
kdweber89 Avatar asked Nov 20 '15 17:11

kdweber89


4 Answers

I know this is an old question and has a marked answer, but no one addressed your actual syntax error. You are combining your method definition with your change_table call. The correct code should be:

class CustomerCleanup < ActiveRecord::Migration
  def change
    change_table(:customers) do |t|
      t.remove :fax
      t.remove :phone
    end
  end
end
like image 61
OzBarry Avatar answered Oct 19 '22 08:10

OzBarry


You can remove multiple columns in a single statement with the remove_columns method

def up
  remove_columns :customers, :fax, :phone
end

But you'll have to define a separate down method if you want to be able to roll back.

like image 44
Toby 1 Kenobi Avatar answered Oct 19 '22 07:10

Toby 1 Kenobi


Have you tried:

def change
  remove_column :customers, :fax
  remove_column :customers, :phone
end

In case you are using rails version lower than 3.x

def self.up
 remove_column :customers, :fax
 remove_column :customers, :phone
end

def self.down
  # do something on rollback here or just do nothing
end
like image 6
Long Nguyen Avatar answered Oct 19 '22 06:10

Long Nguyen


If you want to remove column's from any table by running a migration then try this

rails g migration remove_columns_from_table_name field_name:datatype field_name:datatype

replace table_name with the table from which you want to delete the columns and field_name:data_type with the columns and the datatype of columns you want to remove.

The migration file will look like this

class RemoveColumnsFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type
    remove_column :table_name, :field_name, :data_type
  end
end

and then run the migration

rake db:migrate

And you can also delete the columns directly from your rails console by doing something like this

ActiveRecord::Migration.remove_column :table_name, :column_name 
like image 4
farz bhullar Avatar answered Oct 19 '22 08:10

farz bhullar