Tuesday, April 07, 2009

Finding recursive objects in ActiveRecord in Rails

Here's the issue, say you wanted to find all the students that are in a course (avoiding the 'class' keyword) with you. And say you had models that looked like this...

Class Student <>
has_many :courses

Class Course <>
has_many :students

You might try this in the Student class...

Student.find :all, :include => { :courses => :students }, :conditions => [' = ?',]

But, of course, this would only return self.

To find the classmates, you need to find the name of the alias used on the joined table and put your condition there. Rails will probably give it an alias like 'course_students'. You can confirm this by running the query with a condition on the course table and looking in the logs. Once you know the name of the aliased table you can do this...

def class_mates
Student.find :all, :include => { :courses => :students }, :conditions => [' = ? and != ?',,], :group => ''

This will return all students that are in a class with you, and it will remove you from the list.

Now, if you want to find out how many classes they are in together, that's trickier. I've only been able to do that with find_by_sql.

Let me know if you find a better way.

No comments:

Post a Comment