jnoh
jnoh

Reputation: 95

how to only :include based on a conditional statement

I'm trying to grab Posts and only the comments that belong_to that Post based on a conditional:

ie.

# Grab all posts but only include comments that have been approved.
Post.all(:include => :comments, :conditions => ['comments.approved = ?', true])

Update July 20, 2011 10:11 EST

To clarify, I'm trying to grab all posts and only the comments of that post by a specific user.

def grab_posts_and_only_comments_from(user)
   {:include => [:comments], :conditions => ['comments.user_id = ?', user.id]}
end

UPDATED JULY 20, 2011 11:34 EST

Answer in the comment of the checked answer.

Upvotes: 3

Views: 4953

Answers (2)

fl00r
fl00r

Reputation: 83680

Just add new association approved_comments

class Post < AR::Base
  has_many :comments
  has_many :approved_comments, :class_name => "Comment", :conditions => { :approved => true }
end

Post.includes(:approved_comments)
# or for Rails 2.x
Post.all(:include => :approved_comments)

EDIT

Post.includes(:approved_comments).where(:approved_comments => {:user_id => user.id})

Upvotes: 2

cailinanne
cailinanne

Reputation: 8372

Post.includes(:comments).where("comments.approved = ?", true)

The documentation on this feature is much improved in the EdgeGuides. Check out Section 12.2 here.

Upvotes: 4

Related Questions