named_scope with at least one association

How would I write a named_scope that checks if the parent has at least one associated child?

For example, class Post < ActiveRecord::Base   has many :comments

  named_scope :commented_on, :conditions => "comments.count > 0"

class Comment < ActiveRecord::Base   belongs_to :post

Thanks,             jeff

i think use named_scope is not elegant way. use class method? no idea.you can give me your sample proj.i can test this way.

i got it. reference this url: http://refactormycode.com/codes/209-rails-has_many-count

sample code:

class User

  has_many :messages do
    def by_type(type, options={})

      options[:count_only] ||= false
      messages = find(:all, :conditions => [ 'type = ?', type ])

      options[:count_only] ? messages.size : messages
    end
  end

end

OPTION 1: without helper in view

<h1>Messages:</h1>

<ul>
  <li>Industry Expert: <%= current_user.messages.by_type('Industry Expert', :count_only => true) -%></li>

  <li>Media: <%= current_user.messages.by_type('Media',           :count_only => true) -%></li>

  <li>PR: <%= current_user.messages.by_type('PR',              :count_only => true) -%></li>

</ul>


How would I write a named_scope that checks if the parent has at least one associated child?

First, its better to describe the problem a liitle bit, what I undestand if you want to find only the post that have post, Isnt it ?

Look this example : I wrote by heart, so probably you will have some errors describe Post, "find methods" do   context "find recent comments" do     before :each do       (1..10).each {|n| Comment.create(valid_comment_attributes) }       post = Post.create! valid_post_attributes     end

    it "should not return post with no comments" do       Post.commented_posts.should_not include post     end   end end

So you need to include the comments, but the normal :include => :comments make by default I think make LEFT OUTER join, and what you need is a INNER JOIN, so you can specify that in the :join parameter.

named_scope :commented_posts, lambda { {:joins => 'INNER JOIN comments ON comments.post_id = posts.id'}}

its that enough , maybe, but you will discover after a while a problem some problems like, that you have repeated_posts, and then you should and remove the duplication in another named_scope, or in a the same one

it "should not have repeated post" do   post = Comment.create(valid_comment_attributes :post=>Post.first)   Post.commented_posts.should have_exactly(10).posts end