11.12.07
Getting friendly with ActiveRecord (without Rails)
I’ve been puttering around Ruby and Rails for a while now but it’s been mostly surface-level stuff. Following examples, customizing little things here and there. But I haven’t really dived in and gotten my hair wet.
Since I’m off the merb wagon the next task on the list was getting more familiar with ActiveRecord without getting bogged down in Rails and all things Webish.
My starting point was the excellent tutorial that I’m, in some ways, going to restate in this blog.
I started by connecting to MySQL and creating a database (TaskList) and a task table:
CREATE TABLE tasks ( `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) DEFAULT NULL );
I deviated from the tutorial slightly here by adding AUTO_INCREMENT to the id column. This makes creating the objects a little easier because I can let SQL worry about their ID assignments.
Next I took the sample code from the tutorial, customized it for my settings, and added a little flare at the end:
require 'rubygems' require 'active_record'ActiveRecord::Base.establish_connection({ :adapter => “mysql”, :username => “root”, :database => “TaskList” }) # define a simple model class Task < ActiveRecord::Base end eat = Task.create “title” => “Eat” drink = Task.create “title” => “Drink” bemerry = Task.create “title” => “Be Merry” Task.find(:all).each { |t| puts t.title }
The program output is:
Eat Drink Be Merry
Running it subsequent times adds new tasks with the same values:
Eat Drink Be Merry Eat Drink Be Merry
So nothing ground breaking here. I read a tutorial. I did what it said. It worked. Life is good.
Now it’s time to start branching out a little. Things I want to do now are:
- Add support for task states (start with static and add support for user defined)
- Have the ability to assign tasks to users
- Add a due date to tasks
This should give me the basics for some simple relations. With that foundation I should have enough footing with ActiveRecord that I’m ready to move on to something else.
Jeff said,
November 12, 2007 at 10:04 pm
Glad to see another .NET developer taking Ruby for a spin. I think you’ll find ActiveRecord to be a really rewarding library to work with.
Creating a simple one to many relationship using Ruby, ActiveRecord and MySQL | Ghost On Third said,
November 13, 2007 at 12:45 am
[...] Last time I used ActiveRecord to persist basic tasks. On the list of features to implement was task state such as “New” or “Complete”. [...]