Reputation: 549
I have one array, which are IDs from one ActiveRecord table. so I would like to sort that array based on last name which is associated with that ID...how can I do that? To clarify: array @students=[], inside are IDs and I would like to sort by Student.find(ID).last Thank you. Dorijan
Upvotes: 1
Views: 2619
Reputation: 14851
Based on your comment, you want to do the following:
You should be able to do the following:
Student.where(:id => @ids).order(:last_name).map(&:id)
Breaking this down:
where(:id => @ids)
only selects Students with an ID in the ID array.order(:last_name)
sorts the results by last name.map(&:id)
takes in an array of Students
and returns just the ID column. Essentially, the method in brackets (which is a shortcut for calling id
for each student) is called for each student found, and the return values are assembled into a new array (which will only contain the ids).Some gotchas:
select(:id)
so that you don't pull every column of the Student records from the database.Upvotes: 2
Reputation: 15056
Without fully understanding the question, if you're given a list of id's, you can sort by last_name when you're doing the query:
Student.where("id IN (?)", @students).order(:last_name)
Of course, this assumes that @students is an array of ids and nothing else.
Responding to your comment, I'm not sure why you'd need to do that, but if your @student array is just a list of ids ignorant of the Student model and its attributes, and you would still like to order that array, you can do this:
@students = Student.where("id IN (?)", @students).order(:last_name).collect(&:id)
This will return an array of ids sorted by last name. But again, I don't really know what you have going on behind the scenes, and I'm not sure what you're asking for.
Upvotes: 5