开发者

How to sort an array of objects by an attribute of the objects?

I'm performing this query in a controler and the 'Group' model has_many Users

@group= Group.find(params[:id])

@group is being used to render this partial (the partial dumps the users of a group into a table)

<%= render :partial=>"user_list", :locals=>{:users=>@group.users} %>

The local variable 'users' passed to the partial is an array of User objects;

- !ruby/object:User 
  attributes: 
    updated_at: 2011-01-04 21:12:04
    firstname:  Bob
    lastname: Smith
    id: "15"
    group_id: "2"
    created_at: 2010-11-26 12:54:45

How can the user array be sorted by 'lastname'? I've tried several different ways without any luck. Trying to sort by a object attribute inside an array in confusing me. Also, I don't und开发者_运维问答ertand how I could do this with an :order in the query (how to :order not the Group but the Users of each group)?

Maybe I'm not referring to name of the object correctly ('User')? It seems like this should work be it produces a 'no method' error (or a dynamic constant assignment error if 'sort_by' is used without the !):

 users.sort_by! {|User| User.lastname}

Thanks for any help.


I found a method that works from here. I don't understand what the "&" symbol is doing - maybe it's shorthad for "object" since in my case ":lastname" is an attribute of the object that make up the array.

users = users.sort_by &:lastname

note: I don't undertand why but a destructive version won't work. It produces a "undefined method `sort_by!' for #" errror:

users.sort_by! &:lastname


See http://ariejan.net/2007/01/28/ruby-sort-an-array-of-objects-by-an-attribute/

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


It's probably because you've got |User| when User is a class. Try changing it to an un-used variable name, like u, to get:

 users.sort_by! {|u| u.lastname}

The term between the pipes is the name of the variable each item is stored in, as it runs through, not the type of object you've got. This is the same as other Ruby blocks, like do || end, or any other {||}-style block.


You can try putting an order clause in the "has_many :users" line that you have in your Group model

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜