One other thing you could do is add an auto-populating field to the
parent in the relationship. So, say I have a post model, which has_many
:comments. Using a magic field of comments_count, this will be
auto-updated when comments are added or removed from the post. So, I
could get the list in the order you want, by simply doing...
.find(:all, :order_by => ''comments_count DESC'', :conditions
=>
[''comments_count > x''])
And then I can forget about joins etc... Handy magic field name! (Saves
doing a count - note that doing .count on comments still uses a count
statement).
Hope that''s useful...
Andrew
-----Original Message-----
From: rails-bounces@lists.rubyonrails.org
[mailto:rails-bounces@lists.rubyonrails.org] On Behalf Of Chris Schumann
Sent: 03 April 2006 16:31
To: rails@lists.rubyonrails.org
Subject: Re: [Rails] Order By Number of Comments
> Date: Mon, 3 Apr 2006 16:36:15 +0200
> From: Hamza <hamzakc@gmail.com>
> def show_discussed
> @contents.find(:all, :order => "contents.comment.size DESC",
:joins
> =>
> "comments")
> end
As Francois pointed me to, you want sort_by. find returns an array, and
array mixes in Enumerable.
http://www.ruby-doc.org/core/classes/Enumerable.html#M002092
So something like this:
@contents.find(:all)
@contents.sort_by(|x| f(x))
Where f(x) is code that evaluates the number you want to sort on, like
the number of comments... Comment.count(:conditions => "content_id =
?",
x.id)
Chris S
_______________________________________________
Rails mailing list
Rails@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails