views:

204

answers:

1

We are planning to upgrade our application to Rails3. One plugin we've used quite a bit is nested_has_many_through. This plugin seems outdated, and no longer maintained, and simply does not appear to be working in a new Rails3 application.

A simple example:

Author.rb
has_many :posts
has_many :categories, :through => :posts, :uniq => true
has_many :related_posts, :through => :categories

Post.rb
belongs_to :author
belongs_to :category

Category.rb
has_many :posts

Can anyone recommend the best practice way to handle this, or a working Rails3 plugin?

Thanks!!

A: 

I'm more confused by the has_many :related_posts part. Are you trying to essentially join together categorized posts? Like, all posts in 'x' category are considered 'related'? If so, this won't work based on there not being a RelatedPost class, so to fix this at a bare minimum, you'd have to specify :class_name on the association:

has_many :related_posts, :class_name => 'Post', :through => :categories

But secondly, it's probably not the correct approach to begin with. Since any author already has_many posts via the author_id foreign key, there is no sense in trying to weave back through the categories table, instead use grouping logic.

Alternate approaches that clean this up:

Author.rb

has_many :posts do
  def related
    all.group_by(&:category_id)
  end
end
author.posts.related
=> OrderedHash

Of course, all of this is moot if it wasn't what you were trying to accomplish. :P

jenjenut233
I'm inclined to think his example is contrived (hence easily flawed). His question is still fundamentally important. And to the best of my knowledge there is NOT a working solution for nested has many throughs in Rails 3 (a la the old nested_has_many_through for Rails < 2.3)
bjeanes
The latter part of his question mentioned "recommending the best practice". My point was, if your app requires it, there is probably a better mechanism for achieving it. ;) If his example truly is contrived, it would be incredibly helpful to see his actual code.
jenjenut233
Fair enough. There are definitely use cases where a nested has many association (i.e. using multiple INNER JOINs, for the non-Rails folk) is a valid solution, and often the best one.Given "Author -< articles -< subscriptions >- subscribers >-< interests", `Author.subscribers` and `Author.subscriber_interests` would both be candidates for using the nested has many through, in my opinion. The other option is to cache those associations any time the 1st-level associations change, which is less than ideal.
bjeanes