Foxy Fixtures and polymorphic tables

Well, I’m behind on everything, which means a bunch of interesting blog posts are queued up. But this one seemed short enough to warrant a small post.

I’ve always hated fixtures for the same reason that other people hate them, but nonetheless, I’ve bit the bullet to use them. Along comes Rails 2.0’s foxy fixtures, and it becomes a little easier.

What it doesn’t detail, however, is how to use your newly foxy fixtures for polymorphic models. If I have a vote model that I can use to vote on any type of table, with the old fixtures, I’d have:

id: 1
account_id: 1
votable_id: 3
votable_type: "Scene"

Normally, you just get rid of the foreign keys since it now checks the belongs_to associations of each model, and you can just use the label names. Same goes with the primary key id. It’ll be autogenerated based on a hash of the fixture label.

account: my_account
votable: eat_hotdog
votable_type: "Scene"

Note that you’re using the association names, and NOT the foreign key name, so you don’t use “_id” anymore (that bit me in the ass for a little bit).

However, you’ll find that with polymorphic models, you won’t be able to do that. Searching around the good ‘ole web lead me to find that Foxy Fixtures originally came from a plugin called Rathole, and at the very end of the README, it states:

Also, sometimes (like when porting older join table fixtures) you’ll need to be able to get ahold of Rathole’s identifier for a given label. ERB to the rescue:

Go John Barnette! That way, you can simply do this in your fixtures as a fall-back:

account: my_account
votable_type: "Scene"



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s