Home > other >  Rails, are the model and database the same?
Rails, are the model and database the same?

Time:12-19

Can anyone explain to me the difference with the model and the database? The database is created and represents the model. If anyone can elaborate I would be grateful, thanks.

CodePudding user response:

The database is the set of tables where you store the data.

The model is the Ruby class that represents a table in your code. That's where you implement the code that interacts with that table and its relationships.

CodePudding user response:

The database is where data is actually stored. The model governs interacting with that data for the rest of the application. The goal is to separate the details of how data is stored from how it is used.

For example, without the model, if the application code wanted to get the name of the current user it might query it directly: select name from user where id = ?. With a model, the application code asks the User model. user = User.find(1); user.name. With a model, the details of how User is stored can change without breaking code that uses it. For example, if you change SQL databases the model will protect you from changes in the SQL dialect.

In Rails the model is generally written with ActiveRecord. This still leaks a lot of information about how the model is stored: one class per table, one object per row, method calls like where reference specific details of the table, and you can still write raw SQL. The Repository Pattern can help to further distance how your data is stored from how it is used.

A well designed User model would hide even if the user is stored in the database, maybe it's stored in the cloud and User is doing API calls.

See also...

  • Related