views:

45

answers:

3

Say I have a post and category model, with each post belonging to a category. On pretty much every page, I'm getting the list of categories:

@categories = Category.all

This produces an array of Category objects. Now, say that each category has id and name attributes. When viewing a post, I want to display the category name.

I was originally getting the category name by doing something like this:

@post = Post.find(params[:id], :include => :category)

However, I realize that I already have the @categories array. It seems unnecessary to :include when I already have a list of categories. So, instead, I'm now performing a find on the array:

category = @categories.find { |category| @post.category_id == category.id }.name

This works and reduces the number of queries. My question is if this is the best way to tackle reducing the number of queries (without caching)?

+2  A: 

That's perfectly sensible.

The only risk (and it's a miniscule one) is that you are possibly subject to a race condition. For example, someone could change the post's category after you fetched the categories list, or they could update the list of categories, and what you're showing would no longer be correct. Subsequently, if they, say, clicked on a category name to get a list of all posts with that category, they'd probably get an error unless you were handling that sort of thing.

IMO, that's an awfully small price to pay, though.

John Feminella
good point. unf. no votes left :)
ilya.devyatovsky
+1  A: 

The only issue here would be when you decide you don't need the categories list anymore and try removing it.

Otherwise you got a good solution.

ilya.devyatovsky
A: 

And what if you have a large number of categories? Are you still going to be fetching them all? Doing an :include is much better as SQL will always win over Ruby.

Ryan Bigg
I only envisage a maximum of say... 20 categories. I'll always need to fetch these categories.
Homar