简体   繁体   English

如何使用RAILS 2.3.x的一个查询将activerecord数据集拆分为两半?

[英]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) 数据集看起来像这样(模型WF具有id,widget_id,feature_id,状态为字段)

id widget_id feature_id status id widget_id feature_id status


1 1 23 1 1 1 23 1

2 1 45 1 2 1 45 1

3 1 89 1 3 1 89 1

4 2 41 1 4 2 41 1

5 1 10 0 5 1 10 0

6 1 90 0 6 1 90 0

7 1 83 0 7 1 83 0

8 2 45 1 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 of status) 什么可能是我的activerecord查询,它允许我写一个语句和结果组自己这样的东西(根据状态过滤)

a,b = [23,45,89,41,45][10,90,83] a,b = [23,45,89,41,45] [10,90,83]

If you want to do this with only one SQL query, use group_by : 如果只想使用一个SQL查询执行此操作,请使用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). 这将返回一个带有两个键/值对的OrderedHash(假设状态为0或1)。 The key of each pair will be the status and the value will be an array of WF instances having that status. 每对的密钥将是状态,值将是具有该状态的WF实例的数组。

You can further manipulate the returned OrderedHash using any Enumerable method (like sort, sort_by, map, etc.) 您可以使用任何Enumerable方法(如sort,sort_by,map等)进一步操作返回的OrderedHash

To get the output you want as a, b you need to add the following lines: 要获得您想要的输出,b,您需要添加以下行:

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

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

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