Search code examples
ruby-on-railspostgresqlrubymine

Migration issue in Ruby-on-rails


Hey guys, when I first begin a rails project, the model user was designed and created. After all the migration part, it successful created the table "users" at postgres. Well, then after doing some changes during the project, I realized that was missing an attribute/new column at the table.

So what I did was delete the table users from postgres and add a new column at my first migration ruby class:

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :password
      t.string :email
      t.string :authorization_token //this is the new attribute that I insert
      t.datetime :created_at
      t.datetime :updated_at

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

So, when I run again the db:migrate hopping that a new user table will be created with the new attribute :authorization_token, it doesn't work, but with no errors.

(I know that I should not remove the table, there is another smart way to do it)


Solution

  • Migrations are run once & stored in the database as having been used (take a look in the schema_migrations table). You could try using rake db:migrate:reset to re-run your initial migration, but it's better to just add new migrations (you won't want to blow away your database when it has data in it) as follows:

    script/generate migration add_authorization_token_to_users authorization_token:string

    which will generate something similar to the following:

    class AddAuthorizationTokenToUsers < ActiveRecord::Migration
      def self.up
        change_table :users do |t|
          t.string :authorization_token //this is the new attribute that I insert
        end
      end
    
      def self.down
        remove_column :users, :authorization_token
      end
    end
    

    To see how add/remove column, change_table, etc work, take a look at ActiveRecord::ConnectionAdapters::SchemaStatements at http://api.rubyonrails.org or http://guides.rubyonrails.org/migrations.html