简体   繁体   English

按预定列表排序记录的最佳方法

[英]Best way to order records by predetermined list

In order to keep things simple I have avoided using an enum for an attribute, and am instead storing string values. 为了简单起见,我避免为属性使用枚举,而是存储字符串值。

I have a list of all possible values in a predetermined order in the array: MyTypeEnum.names 我在数组中以预定顺序列出了所有可能的值: MyTypeEnum.names

And I have an ActiveRecord::Relation list of records in my_recs = MyModel.order(:my_type) 我在my_recs = MyModel.order(:my_type)有一个ActiveRecord :: Relation记录列表

What is the best way to order records in my_recs by their :my_type attribute value in the order specified by the array of values in MyTypeEnum.names ? 按myType属性值按MyTypeEnum.names中的值数组指定的顺序对my_recs中的记录进行排序的最佳方法是什么?

I could try this: 我可以尝试这样:

my_recs = MyModel.order(:my_type)
ordered_recs = []
MyTypeEnum.names.each do |my_type_ordered|
  ordered_recs << my_recs.where(:my_type => my_type_ordered)
end

But am I killing performance by building an array instead of using the ActiveRecord::Relation? 但是我是否通过构建数组而不是使用ActiveRecord :: Relation来降低性能? Is there a cleaner way? 有没有更清洁的方法? (Note: I may want to have flexibility in the ordering so I don't want to assume the order is hardcoded as above by the order of MyTypeEnum.names) (注意:我可能希望在排序方面具有灵活性,所以我不想假定该订单是按照MyTypeEnum.names的顺序进行硬编码的)

You are definitely taking a performance hit by doing a separate query for every item in MyTypeEnum . 通过对MyTypeEnum每个项目进行单独的查询, MyTypeEnum This requires only one query (grabbing all records at once). 这仅需要一个查询(一次抓取所有记录)。

ordered_recs = Hash[MyTypeEnum.names.map { |v| [v, []] }]

MyModel.order(:my_type).all.each do |rec|
  ordered_recs[rec.my_type] << rec
end

ordered_recs = ordered_recs.values.flatten

If MyTypeEnum contains :a , :b , and :c , ordered_recs is initialized with a Hash of Arrays keyed by each of the above symbols 如果MyTypeEnum包含:a:b:c ,则使用上述每个符号作为键的Arrays Hash来初始化ordered_recs

irb(main):002:0> Hash[MyTypeEnum.names.map { |v| [v, []] }]
=> {:a=>[], :b=>[], :c=>[]}

The records are appended to the proper Array based on it's key in the Hash , and then when all have bene properly grouped, the arrays are concatenated/flattened together into a single list of records. 根据Hash的键,将记录添加到适当的Array中,然后在对所有数组进行适当分组后,将这些数组连接/合并为一个单独的记录列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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