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)?