Wednesday, October 17, 2007

Models

RoR, being a model-view-controller architecture, obviously has something called a model. These things are just plain out awesome. They are objects that map directly to the database tables. Their fields are the database columns. And the best part is, the mapping is implicit... no massive amounts of XML mapping files! It's clean, it's intuitive, and best of all, less code to write (which translates to less time spent and less errors)!

Inside the class definition, fields don't need to be specified, as it is implicit that all database columns of the table are part of the model, and getters and setters are all implicit. This means no long list of getters and setters for each field! If there's something special that needs to be done for getters and setters, it's very convenient to just override the defaults.

So what is specified within the class definition then? Well, one of the things is table relations. For example, there are one-to-many relations. Imagine a Store has many Items.

In the Store class definition, you would add:

has_many :items

In the Item class definition, you would add:

belongs_to :store

These two lines specify the one-to-many relation between Store and Item. If you had a Store object and you wanted the items, it would be as simple as:

@items = @store.items

This will retrieve you all of the Items associated to the particular Store object.

There are all sorts of things you can do with relations, and this is only the tip of the iceberg.

Another wonderful thing you can do in models is validation! And RoR has a set list of validation functions that can be used for just about anything. Basically, before a model is saved, RoR runs a validation check on the fields. If any of it fails, the model is not saved, and error messages are created, which can then be displayed to the user. It's absolutely wonderful! Validation methods can be checked out here:

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

Well, that's the general idea of models. It's a very nice way to interface with the database while keeping code writing to a minimal. Enjoy!

W

No comments: