Jason Watkins

Force index with active record find

In Blog on March 17, 2008 at 1:00 am

A small useful tip:

Mysql’s query planner occasionally has trouble picking the right index. I’ve found that normally if you try variations long enough, eventually you find a way to do the right thing. Recently however I ran into one I couldn’t coax.

No big deal you say, after all, that’s what find_by_sql is for no? Only problem is, the query in question was inside a with_scope block, and I really didn’t want to have to find and hardcode sql finders for any variations used by callers. Thankfully, the :from option on find can rescue us: just go ahead and include the force index clause. It’s slightly gross imho, but it works, and might save you some manual sql building.