Foxy Fixtures Explained
As of October, 2006, Rails integrated a plugin called Foxy Fixtures into the core API.
This makes it easier to write fixtures–no more worrying about IDs! What’s more, created_on and updated_on are automatically populated with today’s date! Instead of writing this:
# libraries.yaml
central_library:
id: 1
city: "Toronto"
created_on: <%= Date::today %>
You can write this:
# libraries.yaml
central_library:
city: “Toronto”
Nice, eh? Even better–if you have a multiplicity association (has_many, belongs_to, or has_and_belongs_to_many), your fixture goes from:
# books.yaml
agile_rails:
title: "Agile Web Development with Rails"
published: 2007
library_id: 1
To:
# books.yaml
agile_rails:
title: "Agile Web Development with Rails"
published: 2007
library: central_library
Notice how much more readable and maintainable it is! No more IDs polluting your fixtures, no more worries about putting the right or wrong ID; but simple, easy-to-use names.
Now, if you try this, out-of-the-box, it might not work–there’s a tricky gotcha–all the IDs have changed.
You might have assumed, from the example, that with Foxy Fixtures, central_library has an ID of one.
You’d be wrong if you thought that.
What is the ID? If you look through the test log, you’ll see something like this:
...
Library Load (0.000000) SELECT * FROM `libraries` WHERE (`libraries`.`id` = 9523826)
...
What does that mean? It means, quite simply, that the IDs are assigned through some mechanism out of our control–that you cannot depend on the IDs being anything. (The IDs are not completely random, though; the same fixture will always have the same ID.) The good news is, you don’t really care what the ID is–because you can reference the fixture by name!
And that’s fixtures in a nutshell. So take a few minutes now to modify your Rails fixtures to take advantage of this–the ease (and maintainability) of Foxy Fixtures over regular ol’ fixtures makes it an outstanding addition to the core Rails API.
Tags: fixtures, framework, rails 2.0 Posted in


Leave a Reply