views:

567

answers:

3

When you run:

rake db:migrate

the only files that are being processed are those in db/migrate/ right?

Well since relationships such as one-to-one, one-to-many and many-to-many are defined in the in app/models/ , how does Rails enforce such relationships? After I do my migration and look at the generated database schema, I can't see any foreign key constraints. So it's confusing to me as to how all this works.

+6  A: 

Quite simply it doesn't.

It's due to having to support multiple databases. Some, such as sqlite, don't support foreign keys.

To add foreign keys you have to execute the raw SQL for them.

Garry Shutler
What's the point of declaring has_many, belongs_to, etc. then?
alamodey
To have the correct association between your objects. If the only thing altering your database is the rails application, the app itself should honour the relationships without the database's assistance.
Garry Shutler
I see. I guess the constraints are enforced at the higher application layer rather than the underlying database. Wish some texts made mention of it, I've been baffled over this for some time now.
alamodey
it's worse than just having to support multiple databases - depending on the engine you choose inside MySQL it might support foreign keys or not.
Lolindrath
Rails keep track of the foreign keys, not the database. decalring `has_many` in a model tells rails where those foreign keys are and what their names are. All the database knows is that a table has a field named `comment_id` of the type: integer.
Squeegy
+1  A: 

Garry is right, the constraints are enforced by the application itself. If you really wish to have foreign keys set, the foreign_key_migrations plugin could serve you well, though.

Milan Novota
+2  A: 

As others have said, Rails doesn't really use SQL relationships at all but mimics it in code only. It doesn't actually enforce referential integrity but makes it seem like it does.

There is a small school of thought that you should not use migrations for this very reason, but create and secure your database using raw DDL, because the Rails philosophy is flawed in that it still leaves your data model wide open while providing some security measures (an open safe guarded by lasers, is the way I like to put it). Obviously you lose out on the benefits of migrations (I suppose you could keep migrations and manually add execute statements, as well). See the book Enterprise Rails by Dan Chak; he has a few chapters that discuss this and demonstrates his ideas.

Wayne M