9

我们计划将我们的应用程序升级到 Rails3。我们经常使用的一个插件是nested_has_many_through。这个插件似乎已经过时,不再维护,而且似乎根本无法在新的 Rails3 应用程序中工作。

一个简单的例子:

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

任何人都可以推荐处理这个问题的最佳实践方法,或者一个工作的 Rails3 插件吗?

谢谢!!

4

3 回答 3

7

这是内置于 Rails 3.1:http ://asciicasts.com/episodes/265-rails-3-1-overview

于 2011-06-03T22:34:14.687 回答
0

Rails 3(未经测试,按最相关类别的帖子排序):

类别.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

用法:

related_posts = author.categories.posts
于 2011-02-14T17:04:26.980 回答
0

我对 has_many :related_posts 部分更加困惑。您是否要从本质上将分类帖子合并在一起?就像,“x”类别中的所有帖子都被认为是“相关的”?如果是这样,由于没有 RelatedPost 类,这将不起作用,因此要至少解决此问题,您必须在关联上指定 :class_name :

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

但其次,这可能不是正确的方法。由于任何作者已经通过 author_id 外键拥有了_many 个帖子,因此尝试通过分类表编织回来是没有意义的,而是使用分组逻辑。

清理此问题的替代方法:

作者.rb

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

当然,如果这不是你想要完成的,那么所有这些都是没有意义的。:P

于 2010-09-15T03:12:44.803 回答