views:

34

answers:

2

Hi All,

How do I use both include and join in a named scope? Post is polymorphic

class Post
  has_many :approved_comments, :class_name => 'Comment' 
end

class Comment
  belongs_to :post
end

Comment.find(:all, :joins => :post, :conditions => 
                     ["post.approved = ? ", true],      :include => :post)

This does not work as joins does an inner join, and include does a left out join. The database throws an error as both joins can't be there in same query.

A: 

Have you yet tried simply omitting the :joins part of the ActiveRecord call? In my test case of a has_many association, :include will use a join if your conditions refer to the included table name. For example,

Comment.all :include => :post

will run two queries total: one for comments, and one for their posts. The Rails team says that that is better performance. However, if Rails detects that your conditions need a join,

Comment.all :include => :post, :conditions => ['post.approved = ?', true]

will run one query, since you need it.

Isn't ActiveRecord so smart?

Matchu
A: 

If you want to get all the approved Posts with their Comments you can just do something like this:

Post.find(:all, :include => "comments", :conditions => ['approved = ?', true])

This will give you all the approved posts with all the comments. You should not probably use join as it will result in too huge data set (product columns will be included for each comment related to it).

Dmytrii Nagirniak
Heh. Somehow this didn't even occur to me. It could be possible, though, that for the OP organization by posts isn't what he wants, and maybe he's, say, listing the most recent comments. The question isn't clear there.
Matchu
sorry for not specifying initially...what if Post is polymorphic?..then it returns other POST which are not comments?????
Mark
@Mark, give us you real sample. Not sure exactly what you you want to achieve.
Dmytrii Nagirniak