Archive for ActiveRecord

Fixtures Without Rails

So continuing my series of ActiveRecord Without Rails, I thought I would inspect another popular feature of ActiveRecord, Fixtures.

Fixtures are a great way to populate your database with an expected result set. It makes it easy to prepare your database for testing and presentation to your client.

Why would you do this? Well you’ve already got ActiveRecord without Rails working, and probably are using the Migrations without Rails. So why not continue with fixtures?

Note:

  • I won’t go into getting ActiveRecord working without Rails, please refer to that post. It’s dead simple.
  • All these commands are executed from the root directory of your non-rails application.

Creating the Fixtures Directory

The fixtures will need to be stored somewhere, so we’ll just create the necessary directory for them to enjoy a rather peaceful life.

mkdir -p test/fixtures

Setting up the Rakefile

Now we’ll need a Rakefile. If your not familiar with Rakefiles just create a file called: Rakefile File

Note: :

  • If you were following my ActiveRecord Migrations Without Rails, this is the same Rakefile. I’ve changed the default task to execute to load the fixtures instead. You can opt to continue using the migrate task if you want. Just remember to call either rake migrate or rake fixtures, depending on which task you would like call, that isn’t your default task.
  • If you were not following my ActiveRecord Migrations Without Rails, you can ignore the migrate task.

Your First Fixture

Now we’ll create our first fixture, and save it into test/fixtures/users.yml File. The filename corresponds to the table for where the fixtures will be loaded into.

aizatto:
  name: Ezwan Aizat Bin Abdullah Faiz

Warning:

  • Loading fixtures is destructive. It will destroy everything in the table.
  • This task loads all fixtures into the database. We’ll cover specifying individual fixtures later.

Now the fixture is ready for loading and we execute:

rake

There isn’t much output at all (if you even want to call that output) but you’ll see something like:

(in /path/to/app)

Loading Specific Fixtures

By default all fixtures are loaded into the database. Rather than loading all the fixtures, you can also specify which fixtures you want to load by appending them to a FIXTURES argument.

rake FIXTURES=users,roles 

Embedded Ruby in Fixtures

In the same way like Rails, you can also continue to embed ruby inside your fixtures, giving you more flexibility to your hour models will be loaded.

aizatto:
  name: Ezwan Aizat Bin Abdullah Faiz
  created_at: <%= 1.day.ago %>

Conclusion

So by now you’ve probably accumulated quite a bit of knowledge in using ActiveRecord and its features outside of Rails.

So lets hear it, what else would you like to see?

Comments (2)

ActiveRecord Migrations Without Rails

Continuing exploring ActiveRecord without Rails, I thought I’d look into using Migrations without Rails.

Once again, why?

  • You already are using ActiveRecord without Rails
  • Versionable instances of how your database looked like
  • Database agnostic
  • You forget how to crack out SQL code (happens to me, maybe too much ORM)
  • You want migrations in non Ruby Projects
  • boredom

One thing I’d like to emphasize is that you don’t have to use Migrations for Ruby Projects. You can use them in non Ruby projects as well. Just use them to create a versioned of the database.

By using Migrations, your (Ruby and non Ruby) developers will appreciate that they can easily see what changes were made to the database.

Note:

  • I won’t go into getting ActiveRecord working without Rails, please refer to that post. It’s dead simple.
  • All these commands are executed from the root directory of your non-rails application.

Creating the Migrations Directory

First we need a directory where the migrations will be stored, in this case I’ll use the name ‘db/migrate File

mkdir -p db/migrate

Now we’ll create our first migration, and save it as db/migrate/001_create_users.rb File:

Wonderful

Warning:

  • The numbers prefixed to the migration file’s name (in this case 001) is very important. DO NOT OMMIT THIS.
  • Notice the class name is CreateUsers, this should correspond to a camel case representation of the filename.

Setting up the Rakefile

Now we’ll need a Rakefile. If your not familiar with Rakefiles just create a file called: Rakefile File

Note: The :environment task sets up the ActiveRecord configurations, configure as appropriate/desired

Your First Migration

Executing the migration is dead easy:

rake

If you chose to log the output you’d get something like this:

  SQL (0.004480)   CREATE TABLE schema_info (version integer)
  SQL (0.001514)   INSERT INTO schema_info (version) VALUES(0)
  SQL (0.000000)   SQLite::Exceptions::SQLException: table schema_info already exists: CREATE TABLE schema_info (version integer)
  SQL (0.000246)   SELECT version FROM schema_info
Migrating to CreateUsers (1)
== CreateUsers: migrating =====================================================
-- create_table(:users)
  SQL (0.002094)   CREATE TABLE users ("id" INTEGER PRIMARY KEY NOT NULL, "name" varchar(255) NOT NULL)
   -> 0.0026s
== CreateUsers: migrated (0.0028s) ============================================

  SQL (0.001499)   UPDATE schema_info SET version = 1

Perfect

Note: I am using SQLite in this example, your results may come out differently.

Your Second Migration

Knowing that our first migration works, lets create a second migration and test it out!

Now let’s create another migration: db/migrate/002_create_roles.rb File

And when executing rake Terminal, you should see the new table roles being created!

Wizard!

Moving Between Versions

At this stage we are at at version 2 of the database. But how do we go down to say version 0, before everything existed?

rake VERSION=0

What? You only want to go to version 1?

rake VERSION=1

Okay, enough showing off

Conclusion

That’s it, your ready to use and enjoy ActiveRecord’s Migrations Without Rails!

The Migration’s have a ton of features which you can and should utilize, which including adding indexes, controlling verbosity, renaming tables, dropping tables, and modifying existing tables (adding, renaming, modifying, deleting columns).

Just a whole alot of features, do check out the API for it!

Comments (9)

ActiveRecord Without Rails

Some of you must be wondering, I must be insane to use ActiveRecord outside of Rails. But there are some very compelling reasons.

  • ActiveRecord is an awesome library for Object Relational Mapping (ORM).
  • Other projects might not involve the use of Rails.
  • You want to experiment with ActiveRecord prior to creating a plugin for your Rails project.
  • A library for ORM is already written (why reinvent the wheel?)
  • Your just very bored.

Whatever the case may be, it’s best to be prepared.

Installing ActiveRecord

If you already have Rails installed via RubyGems, then your already set to go. Else install it via:

sudo gem install activerecord

Playing with ActiveRecord

Open up a file, and insert the following:

Now if you are familiar with Rails, this is the same configuration as seen in your database.yml file ( RAILS_ROOT/config/database.yml File). There are more options for how to connect to a database, just check the ActiveRecord::Base.establish_connection documentation.

Moving Database Configuration to Another File

Note: It’s not safe to save your database configuration in the same file as you code. In case you distribute your code, and forget to remove your password. That wouldn’t be a cool scenario. (Well it would also be pointless if you sent your database configuration file as well).

So lets make a database.yml and dump the information in there.

adapter: mysql
database:  database
username: user
password: password
host:      localhost

Now our previous file that utilizes ActiveRecord will look like such:

Playing with ActiveRecord Safely!

And now your set to playing around with ActiveRecord without Rails!

Debugging ActiveRecord SQL Queries

Sometimes you run into problems, and suspect your SQL isn’t generated as it’s supposed to be. But how do we debug this?

This will output it to standard error (in which most cases its) your screen. Sadly this can also clutter your screen.

Debugging ActiveRecord SQL Queries to a File

Now if you know your shell well, you can pipe it to a file via: ruby connect.rb 2>> database.log Terminal. But you may forget to pipe it, or what not.

So replace the line containing ActiveRecord::Base.logger with

Warning: I chose to append (’a') the output to the file. This may result in very large files. You can chose to use overwrite (’w') instead.

From here on you can watch the file with: tail -f database.log Terminal.

Funky/Colorized Logs

Note: If you view the database.log file, you’ll notice the following. This is because ActiveRecord colorizes output for viewing in a terminal. But when viewed as a normal file, you get garbage.

  ^[[4;36;1mSQL (0.000273)^[[0m   ^[[0;1mSELECT count(*) AS count_all FROM users ^[[0m

To disable colorize logging, enter:

Extra Resources

Comments (8)

« Previous entries