Forum: Ruby on Rails Sorting an ActiveRecord hash

Posted by Craig Jolicoeur (craigpj)
on 2006-12-01 16:28
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.

the tags table has the following fields:

id, name, count, updated_at

The query returns the top 20 tags sorted by count into @tags

How can I then sort @tags by the 'name' field so I will have the top 20
tags sorted by alpha name?
Posted by nuno (Guest)
on 2006-12-01 16:33
:order => 'name'
Posted by Craig Jolicoeur (craigpj)
on 2006-12-01 16:35
nuno wrote:
> :order => 'name'

not sure what you mean.  I'm already doing :order => 'count DESC' so I 
can get the tags with the highest count.
Posted by Jamey Cribbs (Guest)
on 2006-12-01 16:38
(Received via mailing list)
Craig Jolicoeur wrote:
> id, name, count, updated_at
>
> The query returns the top 20 tags sorted by count into @tags
>
> How can I then sort @tags by the 'name' field so I will have the top 20
> tags sorted by alpha name?
>
>   

@tags.sort! { |t| t.name }



Confidentiality Notice: This email message, including any attachments, 
is for the sole use of the intended recipient(s) and may contain 
confidential and/or privileged information. If you are not the intended 
recipient(s), you are hereby notified that any dissemination, 
unauthorized review, use, disclosure or distribution of this email and 
any materials contained in any attachments is prohibited. If you receive 
this message in error, or are not the intended recipient(s), please 
immediately notify the sender by email and destroy all copies of the 
original message, including attachments.
Posted by Jamey Cribbs (Guest)
on 2006-12-01 16:44
(Received via mailing list)
Jamey Cribbs wrote:
>> the tags table has the following fields:
>
> @tags.sort! { |t| t.name }
>   

Oops.  That should be:

  @tags.sort! { |a,b| a.name <=> b.name }

or, alternatively:

  sorted_tags = @tags.sort_by { |t| t.name }

Jamey

Confidentiality Notice: This email message, including any attachments, 
is for the sole use of the intended recipient(s) and may contain 
confidential and/or privileged information. If you are not the intended 
recipient(s), you are hereby notified that any dissemination, 
unauthorized review, use, disclosure or distribution of this email and 
any materials contained in any attachments is prohibited. If you receive 
this message in error, or are not the intended recipient(s), please 
immediately notify the sender by email and destroy all copies of the 
original message, including attachments.
Posted by Craig Jolicoeur (craigpj)
on 2006-12-01 16:46
Jamey Cribbs wrote:
> Jamey Cribbs wrote:
>>> the tags table has the following fields:
>>
>> @tags.sort! { |t| t.name }
>>   
> 
> Oops.  That should be:
> 
>   @tags.sort! { |a,b| a.name <=> b.name }
> 
> or, alternatively:
> 
>   sorted_tags = @tags.sort_by { |t| t.name }
> 

excellent.  thanks for the help Jamey.  I was trying

@tags.sort! { |t| t.name }

myself already and getting errors.  I didn't realize I needed to use the 
<=> syntax.
Posted by Michael Schuerig (Guest)
on 2006-12-01 17:32
(Received via mailing list)
On Friday 01 December 2006 16:28, Craig Jolicoeur 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 Schuerig
mailto:michael@schuerig.de
http://www.schuerig.de/michael/
Posted by zdennis (Guest)
on 2006-12-01 18:49
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Craig Jolicoeur wrote:
>>
>>   sorted_tags = @tags.sort_by { |t| t.name }
>>
> 
> excellent.  thanks for the help Jamey.  I was trying
> 
> @tags.sort! { |t| t.name }

You can use this with sort_by:

  @tags = @tags.sort_by{ |t| t.name }

There is no "sort_by!" method though.

http://www.ruby-doc.org/core/classes/Enumerable.html#M003156

Zach
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFFcGusMyx0fW1d8G0RAmClAJ98KehW0CLDjMV1ECV8tExtYR9XNQCfTQEI
WQPnSpGZJgSeDIIHZHONxss=
=wVjV
-----END PGP SIGNATURE-----
Posted by nuno (Guest)
on 2006-12-02 10:57
Craig Jolicoeur wrote:
> nuno wrote:
>> :order => 'name'
> 
> not sure what you mean.  I'm already doing :order => 'count DESC' so I 
> can get the tags with the highest count.

Sorry, I did read your question the wrong way !

I wonder if there is a full SQL solution that would be faster than the 
ruby sort...
Posted by askegg (Guest)
on 2006-12-02 11:27
(Received via mailing list)
How about:

@tags = Tag.find(:all, :limit => 20, :conditions => "id != 22 and id !=
47" , :order => "count DESC, name")

I do not have a test environment for this at hand, but depeneding on
your database it should be possible.

http://dev.mysql.com/doc/refman/4.1/en/order-by-op...
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.