Change a column name in rails database.

2019-08-06 12:55发布

问题:

I'm having this table

class CreateEvents < ActiveRecord::Migration
  def self.up
    create_table :events do |t|
      t.integer :subcategory
      t.string :event_name
      t.text :description
      t.string :location
      t.date :date
      t.decimal :price

          t.timestamps
            end
          end

      def self.down
        drop_table :events
      end
end

and i want to change the subcategory to subcategory_id. I tries this one but is not working

ruby script/generate migration RenameDatabaseColumn and then i went to the file which is in db\migrate and edited to look like this

class RenameDatabaseColumn < ActiveRecord::Migration
def self.up
rename_column :events, :subgategory, :subgategory_id
end

def self.down
 # rename back if you need or do something else or do nothing
end
end

then i run the command rake db:migrate put the column is still subcategory. Can you help me please? I'm using rails 2.0

Thank you

回答1:

Did you misspell the column name? isn't it :subcategory? You wrote :subgategory.

class RenameDatabaseColumn < ActiveRecord::Migration
  def self.up
    rename_column :events, :subcategory, :subcategory_id
  end

  def self.down
    # rename back if you need or do something else or do nothing
  end
end