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 undertand 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.
sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse. The key argument specifies a single-arg function to extract a comparison key from each list object.
In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With