开发者

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 = ?', tr开发者_高级运维ue])

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.


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

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


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})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜