简体   繁体   English

加入多态关联

[英]Join on polymorphic association

Hi guys I know that this is really bad idea but I want join three tables for my query on polymorphic association 嗨,大家好,我知道这确实是个坏主意,但是我想加入三个表来查询多态关联

for example 例如

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

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

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

and I need to get something similar to 我需要得到类似的东西

Comment.all(:joins=>:commentable)

of course I can't write exactly such join but I need something that can join this three tables 当然我不能完全写这样的联接,但是我需要可以联接这三个表的东西

I'm writing cimplicate search by several tables User can choose different options Let's say that User has_one Comment and I want select all users who commented something (Article or Post) that includes some phrase So I need something similar to User.all(:joins=>{:comments=>:commentable}, :conditions=>["articles.body LIKE (?) OR posts.header LIKE (?)", value, value]) 我正在通过多个表编写重复搜索用户可以选择不同的选项,假设User has_one Comment ,我希望选择所有对包含某些短语的东西(文章或帖子)进行注释的用户,所以我需要类似于User.all(:joins=>{:comments=>:commentable}, :conditions=>["articles.body LIKE (?) OR posts.header LIKE (?)", value, value])

I suppose that the thing I want to do is impossible because 我想我想做的事情是不可能的,因为

join format 联接格式

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

and I must join tables on commentable_id without any difference for different tables That would be a mess But maybe I am wrong 而且我必须在commentable_id上​​加入表,而对于不同的表没有任何区别,那将是一团糟,但也许我错了

Edits I did next 我接下来做的编辑

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])

I'm still refactoring code and I'll post the result later 我仍在重构代码,稍后再发布结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM