我正在开发Rails 2.3.8 Ruby 1.8.7和PostgreSQL。
当我想搜索小于特定大小的模型时,如何编写查找条件?
例如,我想搜索少于5条评论的主题。
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)])
答案 0 :(得分:0)
这会解决您的问题吗?
Topic.find(:all,:select =&gt;'topics。*,count(comments.id)AS comment_count', :joins =&gt; 'INNER JOIN评论评论.topic_id = topics.id', :group =&gt; 'comments.topic_id HAVING count(comments.topic_id)&lt; 5' )