How to breakup an activerecord dataset into two halves using one query with RAILS 2.3.x?
The dataset looks like this (Model WF with id, widget_id,feature_id,status as fields)
id widget_id feature_id status
1 1 23 1
2 1 45 1
3 1 89 1
4 2 41 1
5 1 10 0
6 1 90 0
7 1 83 0
8 2 45 1
What could be my activerecord query which allows me to write one statement and the result groups itself into something like this ( filter on the basis o开发者_运维问答f status)
a,b = [23,45,89,41,45][10,90,83]
If you want to do this with only one SQL query, use group_by:
all_grouped = WF.all(:select => 'feature_id, status').group_by(&:status)
This will return you an OrderedHash with two key/value pairs (assuming status is either 0 or 1). The key of each pair will be the status and the value will be an array of WF instances having that status.
You can further manipulate the returned OrderedHash using any Enumerable method (like sort, sort_by, map, etc.)
To get the output you want as a, b you need to add the following lines:
a = all_grouped.select{ |k, v| k == 1 }[0].last.map(&:feature_id) # select WFs with status == 1 and keep only the feature attribute
b = all_grouped.select{ |k, v| k == 0 }[1].last.map(&:feature_id) # same with status == 0
This is a far cry from elegant, but to satisfy your requirements you could do something like this:
#model
class WF < ActiveRecord::Base
def self.id_group_on_status
a = WF.find_all_by_status(1).map(&:id)
b = WF.find_all_by_status(0).map(&:id)
a,b
end
end
#somewhere else
a,b = WF.id_group_on_status
精彩评论