2010-08-13 70 views
2

嗨,大家好,我知道,這是非常糟糕的主意,但我想加入我的查詢三個表上的多態關聯加入對多態關聯

例如

class Article 
    has_many :comments, :as=>:commentable 
end 

class Post 
    has_many :comments, :as=>:commentable 
end 

class Comment 
    belongs_to :commentable, :polymorphic=>:true 
end 

,我需要得到類似的東西

Comment.all(:joins=>:commentable) 

我當然不能寫正是這樣加入,但我需要的東西,可以加入此三個表

我被幾個表寫cimplicate搜索用戶可以選擇不同的選項假設User has_one Comment,我想選擇誰評論的東西(文章或帖子)的所有用戶,其中包括一些短語所以我需要類似的東西User.all(:joins=>{:comments=>:commentable}, :conditions=>["articles.body LIKE (?) OR posts.header LIKE (?)", value, value])

+0

它不應該被'Comment'你的第三類?你到底想做什麼?也許我們可以建議另一種方式來達到你想要的效果。 – 2010-08-13 19:38:35

回答

0

我假設我想要做的事情是不可能的,因爲

加入格式

SELECT column_name(s) 
FROM table_name1 
INNER JOIN table_name2 
ON table_name1.column_name=table_name2.column_name 

,我必須加入對commentable_id表,而不用爲不同的表有什麼區別那將是一個爛攤子,但也許我錯了

編輯 我做下一

User.all(:joins=>"clean sql inner join of three tables on commentable_id", 
:conditions=>[" (comments.commentable_class="Article" AND articles.body LIKE (?)) 
      OR (comments.commentable_class="Post" AND posts.header LIKE (?))", value, value]) 

我還在重構代碼,後來我會後的結果