【问题标题】:Rails3 nested has_many through questionRails3 嵌套 has_many 通过问题
【发布时间】:2011-04-08 09:07:38
【问题描述】:

我们计划将我们的应用程序升级到 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 插件吗?

谢谢!!

【问题讨论】:

标签: ruby-on-rails-3 has-many-through


【解决方案1】:

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

【讨论】:

【解决方案2】:

我对 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

【讨论】:

  • 我倾向于认为他的例子是做作的(因此很容易有缺陷)。他的问题仍然非常重要。并且据我所知,在 Rails 3 中没有一个可行的解决方案嵌套有很多贯穿(就像 Rails
  • 他问题的后半部分提到了“推荐最佳实践”。我的观点是,如果您的应用程序需要它,可能有更好的机制来实现它。 ;) 如果他的示例真的是人为的,那么查看他的实际代码将会非常有帮助。
  • 很公平。肯定有嵌套有许多关联的用例(即,对于非 Rails 人来说,使用多个 INNER JOIN)是一种有效的解决方案,而且通常是最好的解决方案。在我看来,鉴于“作者 -- 订阅者 >-Author.subscribers 和 Author.subscriber_interests 都将成为使用嵌套的候选者。另一种选择是在第一级关联发生变化时缓存这些关联,这不太理想。
【解决方案3】:

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

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

用法:

related_posts = author.categories.posts

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多