2010-08-04 24 views
0

我有這個工作到一定程度,但我正在尋找一些關於如何查詢一對多關係中的兄弟姐妹的輸入,看看是否有更優雅的方式完成這個。ActiveRecord兄弟姐妹在多對多的關係

考慮下面的類

class Post < ActiveRecord::Base 
    has_many :post_categories 
    has_many :categories, :through => :post_categories 
end 


class Category < ActiveRecord::Base 
    has_many :post_categories 
    has_many :posts, :through => :post_categories 
end 

一個帖子由定義可以有多個類別,我會需要這個是顯示在網站上「相關的職位」區域。就像我前面提到我有一個工作版本,這是簡單地做到以下幾點:

Post.find(id, :include => {:categories => :posts}) 

望着日誌,那麼應用程序必須做五個查詢得到,我尋找的最終數據。

任何想法感謝!

回答

3

我看到你與你已經有的唯一的問題是,你可能不想返回與帖子共享一個類別的所有職位。

@post = Post.find params[:id] 
@related_posts = Posts.find(:all, :joins => :post_categories, 
           :select => "posts.*, count(post_categories) post_category_count", 
           :conditions => {:post_categories => {:category => @post.categories}}, 
           :group => "posts.id", :order => "post_category_count desc") 

這將返回最相關的帖子第一,即。那些分享類別最多的人,並且您可以添加限制或分頁以限制返回的結果。

+0

謝謝!我修改了條件聲明以排除原始帖子。我更喜歡散列條件語法,但發現它無法處理不等式條件。我正在使用以下內容: :conditions => [「posts.id!=?AND post_categories.category_id IN(?)」,@ post.id,post_categories.collect(&:category_id)] – bdorry 2010-08-04 16:11:08

0

如果你需要支持大型對象樹,你可能想看看awesome nested set,認爲這可能是矯枉過正的問題。

+0

謝謝,我看了進入這一個,但像你說的那樣看起來像是過度的情況。 – bdorry 2010-08-04 16:14:03