user1653027
user1653027

Reputation: 809

How the migration updates a model in Rails3.0

I am trying to add one column in one table using migration up. I have created migration for that and ran rake db:migrate:up[version] it added the column in my table but I don't see that attribute in my respective model. Am I missing something here to do? Below is my snippet ...

migration 6, :add_role_users do
  up do
    execute <<-SQL
      ALTER TABLE users
        ADD COLUMN role varchar(32) DEFAULT NULL
    SQL
  end
  down do
    execute <<-SQL
      ALTER TABLE users
        DROP COLUMN role
    SQL
  end
end

After running the above migration I don't see below line in my User model

property :role, , String, :length => 32

Please suggest, I am using Rails 3.0 so I can't use migration Change method.

Upvotes: 0

Views: 197

Answers (1)

alexpls
alexpls

Reputation: 1964

Rails automatically detects and assigns model attributes based on your table's columns. For some generic information about how this is done, this guide is invaluable: http://guides.rubyonrails.org/migrations.html

Anyway, here's how I would run a migration that adds a role column to the users table.

  1. In your console, run rails g migration add_role_column_to_users role:string. (Since the migration name ends with "users", Rails will automatically know to apply this migration to the users table. Specifying role:string is just a command line shortcut that automatically adds t.add_column :role, :string to your migration. After running this command you should be able to find your new migration in the db/migrate/ directory of your app.)

  2. In your console, run rake db:migrate to migrate the database to your new schema.

  3. That's it! You should now have a "role" column on your "users" table. You can verify this by entering your Rails console with rails c, and bringing up your user model's column names with User.column_names. You should see "role" there.

Upvotes: 1

Related Questions