Jasdeep Singh
Jasdeep Singh

Reputation: 3326

Generated Rails Models - how will the Migrations run?

I've generated four models in my Rails App and i now want to create the tables for the same models through the migrations.

The blanks migrations are sitting there in my /db/migrate folder, now, in what sequence will the Migrations run if i do rake db:migrate

And what should i do to ensure that my tables are generated properly. Should i go ahead and define the associations in my models and then run the migrations?

Because, if i run them as they are, how is Rails gonna figure out the t.references part of the Migrations??

Please help.

Upvotes: 1

Views: 236

Answers (2)

Pan Thomakos
Pan Thomakos

Reputation: 34350

You don't actually need to use references (they don't enforce foreign keys). References may only makes things easier for you to read if you prefer that syntax. These two migrations are equivalent:

create_table :posts do |t|
  t.references :category
end

create_table :posts do |t|
  t.integer :category_id
end

Also, the migrations will be run in the order in which they are defined (i.e the order in which they were created).

Upvotes: 4

Daniel Pietzsch
Daniel Pietzsch

Reputation: 1389

A migration is not directly linked to your model. Before running a migration, you don't need to worry about putting stuff (e.g. associations) in the models or leaving them out. A migration is just a recipe to create or modify a database table and it's fields/columns. You can sort out your model's associations before or after running the migrations. It doesn't matter.

Migrations are run in the order of the filenames of your migrations. If you created your migrations via script/generate model YourModelName or script/generate migration MyMigration a timestamp (like 20110201165030 for example) is always prepended to the name of the file. That makes sure the migrations are run in the order you generated them.

The t.references part doesn't need to figure out anything. It only takes the symbol that comes next, makes it a string, appends _id and creates an integer field with that (new) name in your database table. It's just a convention. It certainly does not look into your model for any associations.

(The code examples given here are for Rails 2.3. If you're using Rails 3, I think the generate commands are a bit different).

Upvotes: 3

Related Questions