user899119
user899119

Reputation: 549

Ruby on Rails 3: sort array based on data from ActiveRecord

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

Answers (3)

Ryan Brunner
Ryan Brunner

Reputation: 14851

Based on your comment, you want to do the following:

  • Take in a list of IDs of students as input
  • Return a list of IDs ordered by the student's last name in the database.

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:

  • If an ID doesn't exist in the database, it will be excluded from the results - if your result array is smaller than your input array, you may be trying to access a record that no longer exists.
  • If the Students table has a lot of columns, you may want to consider calling select(:id) so that you don't pull every column of the Student records from the database.

Upvotes: 2

Sean Hill
Sean Hill

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

cpjolicoeur
cpjolicoeur

Reputation: 13106

Student.find( @students ).sort_by { |s| s.last_name }

Upvotes: 0

Related Questions