Multiple Nested Includes

Perhaps I tried this before and it didn’t work for me, but through some trial and error I figured out how to do nested includes in Rails. This means you can join a join of a joined table without ever having to mess with the join syntax. Of course you also get all of the other cool benefits of using Rails relationships.

My previous article on the subject touched on using single nested includes, but didn’t touch on multiple nesting. Here’s how you do it.

Take the following classes and relationships:

class A < Base
  has_many :B
  #relationship to C via the join table (B)
  has_many :C,  :through => :B
end

class B < Base
  belongs_to :A
  has_many :C
  has_many :D
end

class C < Base
  belongs_to :B
  belongs_to :D,
    :include => :A
end

class D < Base
  has_many :C
  has_many :B
    :through => :C,
    :include => :D
end

Say you want to search on A, and include B, C, D. All you need to do is:

A.find(:all, :include => {:B => {:C => 'D'}})

You simply keep embedding Hashes for each relationship. You can apparently do this indefinitely. So also joining an ‘E’ model that belonged to D would require:

A.find(:all, :include => {:B => {:C => {:D => 'E'}}})

Just another one of the really nifty and less advertised features of Rails.

Posted by chrisp Mon, 12 Feb 2007 06:23:00 GMT


Comments

Leave a response

Leave a comment