Interacting with ActiveRecord through the Rails Console (irb) in Ununtu 10.10

Post to Twitter

Rails and Ruby have quickly grown in popularity over the past few years. I think a lot of Ruby’s growth no doubt can be attributed to Ruby on Rails. In this article I’m going to run over some of the ways you can interact with ActiveRecord through the Rails console (irb).

Keep in mind this will be a very minimal and basic introduction to ActiveRecord and the Rails console (irb). There is much more you can do than than what I’ll present here today.


Note: If you don’t already have a working Ruby on Rails installation make sure to visit my article on how to setup Rails, Ruby, and SQLite on Ubuntu.

I’m using Ubuntu 10.10 so you will need to adjust certain commands to work with your OS of choice if its not Ubuntu. I use Ubuntu for my Ruby on Rails development simply because I find the environment much more suitable for building Rails web apps. Mac OS X also works very well with Rails however I’ve had issues with Windows and certain ruby Gems so I tend to avoid any Rails development now on Windows systems. For this article though any OS capable of running Ruby and Rails ought to work.

I’m using Rails version 3.0.1 and Ruby version 1.9.2p0.

In my home directory I created a folder called repository and then moved into that folder to create my Rails web app:

$ mkdir repository && cd repository
$ rails new myproject
$ cd myproject

At this point a default database in SQLite will be built for us so we can specify a model now and then we will build the table for the new database:

$ rails generate model Monster name:string description:text hitpoints:integer

If we peek at the newly created db/migrate/XXXX_create_monsters.rb file we will see this:

class CreateMonsters < ActiveRecord::Migration
  def self.up
    create_table :monsters do |t|
      t.string :name
      t.text :description
      t.integer :hitpoints

      t.timestamps
    end
  end

  def self.down
    drop_table :monsters
  end
end

This code was generated when the model was generated. Let’s use this code via rake to create the table in the SQLite database:

$ rake db:migrate

The table is now created in the database so at this point we can launch the Rails console:

$ rails console

Please keep in mind from here forward the console command will be preceded with the > symbol. Comments are preceded with the # symbol. I had to pad the code a bit because the WordPress plugin or theme I’m using was hiding the underscore character and you had to scroll for it.

Lets see if indeed our columns made it into the table. Take the table name (Monster) and simple run it as a command:

> Monster

You should see something like this:

# Output from running "Monster" command
=> Monster(id: integer, name: string, description: text, hitpoints: integer, created_at: datetime, updated_at: datetime)
#

Note: The id, created_at and updated_at are added by default and you don’t need to worry about them for this article.

Let’s create a new Monster record. You can use the new or create functions for this, the difference is create will create and save the new record for you. With new you must explicitly call the save after. I’m going to use create:

> Monster.create(:name => "Beholder", :description => "The beholder is a fictional monster in the Dungeons & Dragons fantasy role-playing game. It resembles a floating orb of flesh with a large mouth, single central eye, and lots of smaller eyestalks on top with deadly magical powers.", :hitpoints => 50)

Results if everything went well:

Now to be sure our record really is there let’s try to get it back. There are several ways you can do this.

To find every record we do this:

# find(:all)
> Monster.find(:all)
#

Since there is only one record it just returns the one record back to us. Looking at that record though we can see ActiveRecord gave it an id value of 1. We can get the record back using that id like so:

# find(:id)
> Monster.find(1)
#

In addition, we could have used the commands below since there is only on record we will always get that record back. When we have two or more records though the find(:last) obviously won’t work anymore to return this record back.

# Other ways to find records: find(:first), find(:last)
> Monster.find(:first)
> Monster.find(:last)
#

Let’s try to find the record by just using a dynamic finder that makes use of Ruby’s method_missing functionality:

# find_by_name(value)
> Monster.find_by_name("Beholder")
#

Looking at that code you could also do things like:

# find_by_description(value)
> Monster.find_by_description("...blah...")
#

Let’s update the record now. We are going to increase the Beholder’s hitpoints to 100 from 50.

# Find the record and update it
> monster = Monster.find_by_name("Beholder")
> monster.update_attributes(:hitpoints => 100)
#

If true is returned then it worked.

All I did was place the record that was found into a variable and then used that to update the record.

You can verify the update by doing this:

# Verify if the record is updated
> monster
#

Let’s delete the record now (we still have the monster object so this is trivial):

# destroy the record
> monster.destroy
#

Using this method though the record is gone from the database, but we still have a frozen instance of it in the monster variable.

You can verify this like so:

# display the object and verify the record is gone
> monster
> Monster.find_by_name("Beholder")
#

Note: Like creating a new record, there are also two ways to delete a record: delete and destroy. In this case I used the delete method.

You can exit the console by typing:

# Exit the console
> exit
#

Post to Twitter

This entry was posted in Rails, Ruby. Bookmark the permalink.