开发者

Rails3 nested has_many through question

开发者 https://www.devze.com 2023-01-14 06:29 出处:网络
We are planning to upgrade our application to Rails3. One plugin we\'ve us开发者_如何学运维ed quite a bit is nested_has_many_through. This plugin seems outdated, and no longer maintained, and simply d

We are planning to upgrade our application to Rails3. One plugin we've us开发者_如何学运维ed 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!!


This is built in with Rails 3.1: http://asciicasts.com/episodes/265-rails-3-1-overview


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


Rails 3 (untested, orders by posts with most related categories first):

category.rb:

class Category < ActiveRecord::Base
  class << self
    def posts
      Post.joins(:categories).
           where(:categories => select('id').all.map(&:id)).
           group('posts.id').
           order('count(*) DESC')
    end
  end
end

Usage:

related_posts = author.categories.posts
0

精彩评论

暂无评论...
验证码 换一张
取 消