Dynamic finders: modifying find_by_id for legacy tables

leave a comment »

One of my projects at Obtiva integrates heavily with a legacy database that isn’t “rails friendly”. None of the primary keys are named id so I use set_primay_key “model_id” all over the place along with some other workarounds.

I ran into an interesting problem when integrating techno weenie’s restful authentication into an existing user model. The plug-in raised an error when trying to run User.find_by_id and logged a no method error. I quickly found that, in their current state, dynamic finds aren’t aware of a primary key being set.

Since Rails advertises itself as opinionated software the behavior makes sense, however if you’re wanting to write highly portable code for say a plug-in when you might want to put a warning in the instructions. Some of your users can’t rely on a standard Model.find_by_id(1).

For the sake of time, I went ahead and modified the authentication plugin, but it would be nice if find_by_id checked for the set_primary_key and changed it to find_by_primary_key before raising an error. On that note, I think I have an idea for my first simplistic rails plug-in.

UPDATE: Instead of modifying the authentication plugin it is probably a better idea to override the find_by_id method in the User class, which would look something like this:

def find_by_id(id)

Written by syntatic

May 23, 2007 at 3:25 am

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: