0

I'm developing Rails 2.3.8 Ruby 1.8.7 and PostgreSQL.

When I want to search model which has less than specific size, how to write find conditions?

For example, I want to search Topic which has less than 5 comments.

class Topic < ActiveRecord::Base
     has_many :comments
end

class Comment < ActiveRecord::Base
     belongs_to :topic
end

Topic.find(:all,:include => :comments, :conditions => [(which has less than 5 comments)])
DIGITALSQUAD
  • 3,384
  • 3
  • 22
  • 24

1 Answers1

0

Will this solve your problem?

Topic.find(:all, :select => 'topics.*, count(comments.id) AS comment_count', :joins => 'INNER JOIN comments ON comments.topic_id = topics.id', :group => 'comments.topic_id HAVING count(comments.topic_id) < 5' )

Roger
  • 302
  • 1
  • 8