(Ruby 1.9.3-p429; Rails 3.0.6) Recent changes to the way we queue our tests have rendered our last_ids scope:
(Ruby 1.9.3-p429; Rails 3.0.6)我们对测试进行排队的方式的最新更改已经呈现了我们的last_ids范围:
last_ids = tests.where('end_time != 0').
group(:condition1, :condition2, :condition3, :condition4).
select('max(id) as id')
logically obsolete. Previously, the tests were queued and completed in the same order as the test record was created so the maximum id for each grouping was also the latest test record. Now, for efficiency, we have a queuing algorithm that no longer guarantees the order of the tests. I have added an "end_time" column to the test table. My solution, so far is too slow to use:
逻辑上过时了。以前,测试按照与创建测试记录相同的顺序排队并完成,因此每个分组的最大ID也是最新的测试记录。现在,为了提高效率,我们有一个排队算法,不再保证测试的顺序。我在测试表中添加了“end_time”列。到目前为止,我的解决方案使用速度太慢:
max_end_times = tests.where('end_time != 0').
group(:condition1, :condition2, :condition3, :condition4).
.maximum(:end_time)
which yields a hash: {[:condition0, :condition1, :condition2, :condition3]=>:endtime}. then I do as follows:
产生一个哈希:{[:condition0,:condition1,:condition2,:condition3] =>:endtime}。然后我做如下:
hash.each_pair do |key, value|
last_ids << tests.select(:id).
where(condition0: [key[0]]).
where(condition1: [key[1]]).
where(condition2: [key[2]]).
where(condition3: [key[3]]).
where(end_time: [value]).
map(&:id)[0]
end
This works, but it is entirely too slow.
这有效,但它太慢了。
So...does anyone know how to match the maxumum(:end_time) for a given grouping but only return the :id's? (all i need to get from the database is the :ids of the lastest test for each grouping).
所以...有没有人知道如何匹配给定分组的maxumum(:end_time)但只返回:id's? (我需要从数据库获取的是:每个分组的最新测试的ID)。
EDIT: clarification.
1 个解决方案
#1
0
ActiveRecord::Calculations#pluck
http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
Edit: If you don't have #pluck
, you could still probably do this in one query & a #map
with:
编辑:如果你没有#pluck,你仍然可以在一个查询和#map中执行此操作:
tests.where('end_time != 0').
group(:condition1, :condition2, :condition3, :condition4).
select('id, max(created_at)').map(&:id)
#1
0
ActiveRecord::Calculations#pluck
http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
Edit: If you don't have #pluck
, you could still probably do this in one query & a #map
with:
编辑:如果你没有#pluck,你仍然可以在一个查询和#map中执行此操作:
tests.where('end_time != 0').
group(:condition1, :condition2, :condition3, :condition4).
select('id, max(created_at)').map(&:id)