0

Let's say I have:

class ForumTopic < ActiveRecord::Base
  has_many :forum_posts
  named_scope :number_of_posts, ??????
end

class ForumPost < ActiveRecord::Base
  belongs_to :forum_topic
end

What should I put in ????? to allow searchlogic query like:

ForumTopic.descend_by_number_of_posts

Any help would be very greatly appreciated!

John Topley
  • 113,588
  • 46
  • 195
  • 237
jaycode
  • 2,926
  • 5
  • 35
  • 71

1 Answers1

0

Do you want to order by number of posts, right?

I think it's easier if you use :counter_cache because if you do, you can order just like this:

class ForumTopic < ActiveRecord::Base
  has_many :forum_posts
  named_scope :by_number_of_posts, :order => "forum_posts_count"
end

# controller
ForumTopic.by_number_of_posts.all

To use :counter_cache you'll need to change the association

class ForumPost < ActiveRecord::Base
  belongs_to :forum_topic, :counter_cache => true
end

and create a forum_posts_count column on forum_topics table.

I believe this is it.

Ju Nogueira
  • 8,435
  • 2
  • 29
  • 33