简体   繁体   中英

Sorting a Rails active record

I have a table A(:name, :address, :country_id) . I run this query

ids = [1,2,3]
@result = A.where(country_id: ids)

But, I want to get the results in this order : records containing country_id = 2 first, then 1 and then 3 .

How should I write this query?

Edit :

@people = []
@result.each do |r|
  @people.push([r,r.name])
end

I have an array @people of arrays now and want to sort it. What should be the query now?

Another Edit :

@people.sort_by! {|p| preferred_order.index(p.first.country_id)}

This worked.

You can use sort_by :

ids = [1,2,3]
preferred_order = [2,1,3]

@result = A.where(country_id: ids)
@result.sort_by! { |u| preferred_order.index(u.country_id) }

One option would be adding an extra column

 rails g migration add_sortorder_to_A sort_order:integer

Then add a

before_save :update_sort_order

def update_sort_order
  if self.country_id == 1
    self.update_attributes(sort_order:2)
  elsif self.country_id ==2
    self.update_attributes(sort_order:1)
 ........
end

Alternatively, put your sort_order in the countries and sort on that.

Alternatively, create a dynamic field which will give you the sort_order.

There is probably a more elegant way of doing this, but this should work in a quick and dirty way and allow you to use standard activerecord queries and sorting. (ie you can just forget about it once you've done it the once)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM