views:

30

answers:

1

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

A: 

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

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

Bohdan Pohorilets