1

I have a Partner model that has_and_belongs_to_many Projects, while each Project has_many Sites. I want to retrieve all sites for a given partner (and am not interested in the projects in between at the moment).

I have accomplished what I need through a named_scope on the Site model, and a project.sites instance method that wraps a call to the Site named scope, as follows:

class Partner < ActiveRecord::Base

  has_and_belongs_to_many :projects

  def sites
    Site.for_partner_id(self.id)
  end

end


class Project < ActiveRecord::Base

  has_many :sites

end


class Site < ActiveRecord::Base

  belongs_to :project

  named_scope :for_partner_id, lambda {|partner_id|
    { :include=>{:project=>:partners},
      :conditions=>"partners.id = #{partner_id}"
    }
  }

end

Now, given a partner instance, I can call partner.sites and get back a collection of all sites associated with the partner. This is precisely the behavior I want, but I'm wondering if there's another way to do this using only activerecord associations, without the named scope?

KenB
  • 6,587
  • 2
  • 35
  • 31

1 Answers1

1

I had a similar deep nesting query/collection problem here (I had to threaten to repeat data before anyone would answer my 4 questions, clever): Is it appropriate to repeat data in models to satisfy using law of demeter in collections?

The trick is this gem http://rubygems.org/gems/nested_has_many_through which can do something like this:

class Author < User
  has_many :posts
  has_many :categories, :through => :posts, :uniq => true
  has_many :similar_posts, :through => :categories, :source => :posts
  has_many :similar_authors, :through => :similar_posts, :source => :author, :uniq => true
  has_many :posts_of_similar_authors, :through => :similar_authors, :source => :posts, :uniq => true
  has_many :commenters, :through => :posts, :uniq => true
end

class Post < ActiveRecord::Base
  belongs_to :author
  belongs_to :category
  has_many :comments
  has_many :commenters, :through => :comments, :source => :user, :uniq => true
end

This has super-simplified my queries and collections. I hope you find an answer to your problem, it's a tough one!

Community
  • 1
  • 1
thejonster
  • 156
  • 2
  • 10
  • Thanks, this certainly looks like the ticket! Unfortunately, the available 2.3 branch of the gem is still experimental, and fails some tests. Since my use for it is limited and I have a viable workaround, I think I'll leave things be for now. I will look forward to developing in rails 3.1, though, where this is a built-in default! – KenB Jun 20 '11 at 21:29