DelusionalCode

I'm Sandeep, currently working at Sourcebits Technologies in Bangalore. I am a Ruby developer and an opensource enthusiast. I like to blog about Ruby, Rails & technology.

Home
Archives
Projects
About

Nested has many through in Rails 3.1

04 May 2012 - Bangalore, India

There’s a cool feature implemented in Rails 3.1. You can now have a nested “has many through” relationship. Here’s an example to show what I mean by a “nested hmt”:

class User < ActiveRecord::Base
  has_many :memberships
  has_many :organizations, :through => :memberships

  # => This is not possible in Rails < 3.1
  has_many :deals, :through => :organizations

 def has_deals?
   self.deals.any?
 end
end

As you can see, organizations table here acts as the join table between users and deals, although users has a has many relationship with organizations through memberships. This nifty feature is very useful when dealing with complex relationships and you don’t have to simulate the “has many through” here.

comments powered by Disqus