Rails: paying for convenience.

Wednesday, June 06, 2007 at or around 10:39 AM
eek. that's a whole lot of SELECT *

So I’ve been tinkering for the last couple of days with adding a commenting feature to this blog. One of the things that I’m really starting to notice with rails (and perhaps this is terribly obvious) is that while a lot of stuff is really great, you sure do pay for convenience.

Having gone through the Agile Web Development with Rails book as an intro to rails, I had been working based on some of the patterns discussed there. It’s quite possible that I’m the idiot in this situation, but all the same, it’s a bit frustrating. For example in building comments, there are comments, which belong to entries. There’s also a commenter, which belongs to each comment—a simple enough set of relationships.

However as I’m building this, it appears that rails is going SQL crazy. First, it’s making the initial SELECT query to get the entry… that’s fine. And then another query to get the comments for that entry… also fine. But after that, rails decides to make an additional SELECT * query for each comment’s commenter (that's a mouthful).

I sure would have hoped that by using the has_many and belongs_to statements in the models, rails would have been smart enough to have seen this should be a join. Being the rails newbie that I am, I don’t seem to see any real way of making rails do that (outside of writing my own SQL—which isn’t not writing the point of using rails?).

I’ve finally decided to wrap a little of my own logic around it and specifically work with the commenter_id field in the comments table to avoid the extra SELECT statements which (frankly) seems like a bit of a hack.

Let me say flat out: I am no DBA or rails guru. So, maybe none of this really matters since the queries are small (I’ve always played by the rule of thumb to make your DB queries as efficient as possible, and count for as much as possible)

Maybe the answer is that you can solve all of this by caching, so don’t worry about what kind of SQL rails is using…

And, then again, maybe I’m the idiot who’s missing something really obvious.