views:

52

answers:

2

I have this working to a degree, but I am looking for some input on how to query for the siblings in a one to many relationship to see if there is a more elegant way of accomplishing this.

Consider the following classes

class Post < ActiveRecord::Base
  has_many :post_categories
  has_many :categories, :through => :post_categories
end


class Category < ActiveRecord::Base
  has_many :post_categories
  has_many :posts, :through => :post_categories
end

A post by definition can have multiple categories, what I would need this for is to show a "related posts" area on the site. Like I mentioned previously I do have a working version which is to simply do the following:

Post.find(id, :include => {:categories => :posts})

Looking at the logs the application then has to do five queries to get the end data that I am looking for.

Any thoughts are appreciated!

+2  A: 

The only problem I see you having with what you have already is that you probably don't want to return all posts which share a category with a post.

@post = Post.find params[:id]
@related_posts = Posts.find(:all, :joins => :post_categories,
                              :select => "posts.*, count(post_categories) post_category_count", 
                              :conditions => {:post_categories => {:category => @post.categories}}, 
                              :group => "posts.id", :order => "post_category_count desc")

This will return the most relevant posts first, ie. those which have the most shared categories, and you can either add a limit or paginate in order to limit results returned.

mark
bdorry
A: 

If you need support for large object trees, you might want to look at awesome nested set thought it may be overkill for this problem.

yonkeltron
Thanks, I looked into this one but like you said it looked like overkill for the situation.
bdorry