views:

32

answers:

1

Do I need to re-migrate whenever I change the models in Rails? Can someone tell me what migration really does? I am reading it and I am somewhat confused with the difference between the stuff inside db/migrate and the stuff inside app/models.

For example, if I add a has_one realtionship inside my model, do I need to re-migrate this? Why?

+1  A: 

If your database changes, use a migration. If you're just adding methods to your model, no need to have a migration.

Example:

We start out and we just have first_name, last_name. We want to store those in the database, so we have a migration that does:

/app/models/human.rb

# empty

/db/migrate/xxxxx.rb

add_column :humans, :first_name, :string
add_column :humans, :last_name, :string

Then we get married, so we want to track that

/app/models/human.rb

belongs_to :spouse
  • We need to have a spouse_id field in the database, so we need a migration

/db/migrate/xxxxx.rb

add_column :humans, :spouse_id, :integer
  • We then have a kid.... In fact, we were all kids at one point, but to keep it simple, we'll have Humans and Offspring

/app/models/offspring.rb

belongs_to :human

/db/migrate/xxxxx.rb

create_table ... 
  • However, no need to add anything to the Human migration, since no tables change here. We do need to add:

/app/models/human.rb

has_many :offspring
  • If you want to be able to get at, easily, your first born, you'd just add a method to your model. No need for a migration here:

/app/models/human.rb

def first_born
  offspring.first
end
Jesse Wolgamott
that was very helpful Jesse. Thank you very much for your response.
denniss