I am having trouble understanding ORM in Ruby on Rails. From what I understand there is a 1:1 relationship between tables/columns and objects/attributes. So every record is an object.
Also what exactly is a Model? I know it maps to a table.
What I’m really after is a deeper understanding of the above. Thank you in advance for your help
I’m a Web developer going from PHP to Ruby on Rails.
“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
clientstable, with columnsid(autonum) andname(varchar). Let’s say that it has only one record, id=1 and a name=”Ford”. Then:clientswill map to the model classClient.ford = Client.find(1)fordvariable. You can doford.idand you will get 1. You can doford.nameand you will get the string “Ford”. You can also change the name of the client by doingford.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:
brandstable (with its correspondingBrandmodel) associated via a foreign key to your ford client, you could doford.brandsand you would get an array of objects representing all the records on the brands table that have a client_id = 1.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.