Ruby on Rails: how to migrate changes made on models?

Rui picture Rui · Oct 18, 2012 · Viewed 11.1k times · Source

In a Rails application, how can I migrate the changes I make in models? For instance, I know that if I create a model with command "rails g model Person name:string", a migration will be created as well. However, if after this step I go to the created model "Person" and add a new attribute, will this new attribute be automatically added to a migration for later persistance in database? Or am I looking at this from the wrong side, and an attribute should be added to a migration, and then added to a model?

Regards

Answer

Chris Salzberg picture Chris Salzberg · Oct 18, 2012

You can't really "add" an attribute to a model, you do that by creating the migration file and running it -- Rails figures out what attributes a model has based on what columns are in the database. However, you do need to add a line to the model to whitelist the attribute if you want to be able to update it via mass assignment. That's why you'll often see a line like this in activerecord models:

attr_accessible :name

But that's optional and not essential to adding the attribute.

To actually add the new attribute to your model, first create a migration with:

rails g migration AddAddressToPerson address:string

That will create the migration file in the db/migration/ directory. (The form “AddXXXToYYY” and “RemoveXXXFromYYY” are understood by rails to mean "add (or remove) a new column to the model XXX", see the documentation for details). In this case I've added an attribute named address which is a string, but you could change that to whatever you want it to be.

Then to actually update the database, you need to run the migration with rake:

rake db:migrate

Finally, if you want to allow mass assignment on that attribute, add the attribute to your list of arguments to attr_accessible:

attr_accessible :name, :address

That should do it.