Ramaze by Example - Part 3: Model

November 18, 2008 at 13:40

Filed under: Computing — Pistos @ 13:40

This is part 3 of Ramaze by Example, a tutorial on web development. In Part 2: Base Application, we wrote the main executable Ruby file for our web application.

Now we setup our models. The models are the Ruby classes that allow us to access the data in the database with Ruby objects instead of awkward things like arrays, hashes or long strings. Whatever numbers, strings, dates and things are in the database, we can read from model objects. When we change some data of a model object, a corresponding change occurs in the database. Models act as our read and write interface to the database.

We only have one table, so we only have one model. This one-to-one relationship is typical. If your app has several tables, you’d generally have a model for each one, except perhaps association tables.

So here’s our model code:

class Task < DBI::Model( :tasks )
  def status
    done ? 'done' : 'not done'
  end
end

Pretty simple. Making a model class with M4DBI is as easy as subclassing DBI::Model and passing the name of the table you want to model. Even having an empty class definition would have provided us with a lot of access and manipulation power, but as you can see, I’ve also added a helpful method, status, which we can use to turn the plain boolean done column into a clear, informative string. We’ll see models in action later in the tutorial.

I’ve put this code in a file called task.rb, and situated the file under a src/model/ directory (in accordance with the acquire call in start.rb). Again, this is personal preference. You can setup your application’s directory structure however you wish.

Now let’s learn about the next component of MVC in Part 4: View.

Share This

Related posts:

  1. Ramaze by Example - Part 7: Checking off Tasks
  2. Ramaze by Example - Part 4: View
  3. Ramaze by Example - Part 5: Controller
  4. Ramaze by Example - Part 8: Deleting Tasks
  5. Ramaze by Example - Part 1: Database Schema

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You may use Markdown syntax in your comment.

Powered by WP Hashcash

Powered by WordPress.
Close
E-mail It
Socialized through Gregarious 42