On Friday 01 December 2006 16:28, Craig J. wrote:
I’ve got a query like the following:
@tags = Tag.find(:all, :limit => 20, :conditions => “id != 22 and id
!= 47” , :order => “count DESC”)
My understanding is the ActiveRecord returns an array of hash objects
to @tags. so @tags is actually an array full of hashes.
No! Look for yourself by looking at @tags, e.g. by executing the query
in script/console.
How can I then sort @tags by the ‘name’ field so I will have the top
20 tags sorted by alpha name?
Arguably, tags have a natural ordering by name, therefore it makes sense
for Tag to implement <=>
class Tag
def <=>(other)
self.name <=> other.name
end
end
Then you can just call @tags.sort! and the supplied operator is used.
For good measure you should make Tag Comparable to get a few more
methods for free
class Tag
include Comparable # provides <, <=, ==, >=, >, between?
def <=>(other)
self.name <=> other.name
end
end
Even better, push back the query into your Tag model class. Thus,
@tags = Tag.find(:all, :limit => 20, :conditions => “id != 22 and id
!= 47” , :order => “count DESC”)
becomes
class Tag
def Tag.find_top_20(*excluded_ids)
exclude_ids_condition = excluded_ids.empty? ?
nil :
[‘id NOT IN (?)’, excluded_ids]
tags = Tag.find(:all,
:limit => 20,
:conditions => exclude_ids_condition,
:order => ‘count DESC’)
tags.sort!
end
end
Presumably the excluded ids have some meaning and you really shouldn’t
carry them around by hand. Very probably, what you’re trying to do
belongs as an extension on an association – have a good look at the
docs for associations.
Michael
–
Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/