> 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









> 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
>
> --
>
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Talk" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to 
> [email protected].
> For more options, visit this group at 
> http://groups.google.com/group/rubyonrails-talk?hl=en.
>
>
>



-- 
-------------------------------------
Pedro Del Gallego

Email              :   [email protected]

--

You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.


Reply via email to