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
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.
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