2010-08-13 79 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]) 

我还在重构代码,后来我会后的结果