"From what I understand there is a 1:1 relationship between tables/columns and objects/attributes. So every record is an object."
That is not exactly correct, unless you use the term "object" very loosely. Tables are modelled by classes, while table records are modeled by instances of those classes.
Let's say you have a clients
table, with columns id
(autonum) and name
(varchar). Let's say that it has only one record, id=1 and a name="Ford". Then:
- The DB table
clients
will map to the model class Client
.
- The record will map to a model instance, meaning that you have to create the object and assign it to a variable in order to work with the record. The most common way would be to do
ford = Client.find(1)
- The two columns of the table will map to methods on the
ford
variable. You can do ford.id
and you will get 1. You can do ford.name
and you will get the string "Ford". You can also change the name of the client by doing ford.name = "Chevrolet"
, and then commit the changes on the database by doing ford.save.
"Also what exactly is a Model? I know it maps to a table"
Models are just classes with lots of very useful methods for manipulating your database. Here are some examples:
- Validations: Besides the typical db-driven validations ("this field can't be null") you can implement much complex validations in ruby ("this field must be a valid email" is the most typical one). Validations are run just before you invoke "save" on a model instance.
- Relationships: The foreign keys can also be mapped onto models. For example, if you had a
brands
table (with its corresponding Brand
model) associated via a foreign key to your ford client, you could do ford.brands
and you would get an array of objects representing all the records on the brands table that have a client_id = 1.
- Queries: Models allow you to create queries in ruby, and translate them to SQL themselves. Most people like this feature.
These are just some examples. Active record provides much more functionalities such as translations, scoping in queries, or support for single table inheritance.
Last but not least, you can add your own methods to these classes.
Models are a great way of not writing "spaguetti code", since you are kind of forced to separate your code by functionality.
- Models handle database interaction, and business logic
- Views handle html rendering and user interaction
- Controllers connect Models with Views