Dynamic finders: modifying find_by_id for legacy tables
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) find_by_primary_key(id) end