2010-09-05 76 views
9

我們計劃升級我們的應用程序到Rails3。我們用過的很多插件是nested_has_many_through。這個插件看起來過時了,不再維護,而且看起來並沒有在新的Rails3應用程序中工作。Rails3嵌套has_many通過問題

一個簡單的例子:

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中的插件?

謝謝!

+1

哈哈我剛找到你的fork http://github.com/releod/nested_has_many_thr記得這個問題,並且來到這裏告訴你所有關於叉子的事情。然後我看到了你的用戶名。良好的工作,我剛剛在我的Rails 3應用程序上進行了測試,它(大部分)都在工作。 我一直花費整晚試圖直接修補Rails根據https://rails.lighthouseapp.com/projects/8994/tickets/1152-support-for-nested-has_many-through-associations但卡住了。我將以叉作爲模板開始,現在我可能會更進一步! – 2010-09-23 13:24:49

+0

+1 http://github.com/releod/nested_has_many_through你的rails3 fork也適用於我,直到rails 3.1 – clyfe 2011-03-21 15:26:25

回答

0

我更加困惑has_many:related_posts部分。你是否試圖基本上將分類的帖子結合在一起?比如,'x'類別中的所有帖子都被認爲是「相關的」?如果是這樣,這是不行的基礎上有沒有作爲一個RelatedPost類,所以在最低限度解決這個問題,你必須註明:CLASS_NAME對聯想:

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

但其次,它可能不是開始的正確方法。由於任何作者已經通過author_id外鍵發送了has_many文章,因此嘗試通過類別表編織回來沒有任何意義,而是使用分組邏輯。

是打掃一下備用方案:

Author.rb

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

當然,所有這一切都是沒有實際意義,如果它是不是你試圖完成。 :P

+2

我傾向於認爲他的例子是人爲設計的(因此容易有缺陷)。他的問題仍然非常重要。並且據我所知,在Rails 3中沒有可嵌套的工作解決方案。(Rails <2.3)的舊nested_has_many_through – 2010-09-22 07:40:20

+0

他的問題的後半部分提到「推薦最佳實踐」。我的觀點是,如果你的應用需要它,可能有更好的機制來實現它。 ;)如果他的例子真的是人爲的,那麼看到他的實際代碼將會非常有幫助。 – jenjenut233 2010-09-23 22:41:35

+1

夠公平的。肯定有使用情況,其中嵌套有許多關聯(即使用多個INNER JOIN,對於非Rails民間人士)是一個有效的解決方案,並且通常是最好的解決方案。 在我看來,鑑於「作者 - <文章 - <訂閱> - 訂戶> - <利益」,'Author.subscribers'和'Author.subscriber_interests'都是使用嵌套的候選人。另一種選擇是在第一級關聯發生變化時緩存這些關聯,這並不理想。 – 2010-09-23 22:54:22

0

的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