Liker
Liker

Reputation: 2267

Why in Rails table fields are defined in migrations but not in models?

I am studying Ruby on Rails and confused with structure of files and code.. Why in Rails table fields are defined in migrations but not in models? I know, what are models needed for. However rails like any framework is aimed to make developer work easier and put all dirty work under the hood. Moreover, we define relationships of database both in models and migrations? But we could define them just in one place and automatically transfer to another..

Upvotes: 0

Views: 48

Answers (1)

user229044
user229044

Reputation: 239471

Why in Rails table fields are defined in migrations but not in models?

They're not. They're defined in the database. Once your migrations have run, you can delete them and the models will still be fully aware of the definition of their tables. You can also build and run a Rails app while never defining a single migration, if you chose instead to build your database via other means like manually running SQL statements or a GUI tool.

Moreover, we define relationships of database both in models and migrations?

No, only in models. Migrations are for introducing database changes, nothing more. Their purpose is codifying database changes in such a way that they can be deployed along with their dependent changes to application code.

But we could define them just in one place and automatically transfer to another..

Your relationships are defined in one place: The associations in your models. Your database can add additional constraints like foreign keys, but as far as Rails is concerned, if you don't have an association linking two models, those models are not linked.

Upvotes: 4

Related Questions