正在对 Rails 个活动记录进行排序

Sorting a Rails active record

我有一个tableA(:name, :address, :country_id)。我运行这个查询

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

但是,我想按以下顺序获得结果:records containing country_id = 2 first, then 1 and then 3

我该如何写这个查询?

编辑:

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

我现在有一个数组@people of arrays,我想对它进行排序。现在应该查询什么?

另一个编辑:

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

这有效。

您可以使用 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) }

一个选项是添加一个额外的列

 rails g migration add_sortorder_to_A sort_order:integer

然后加一个

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

或者,将您的 sort_order 放入国家/地区并对其进行排序。

或者,创建一个动态字段,它将为您提供 sort_order。

可能有一种更优雅的方法来执行此操作,但这应该以一种快速而肮脏的方式工作,并允许您使用标准的 activerecord 查询和排序。 (即,一旦完成一次就可以忘记它)