Rails收集随机记录

时间:2015-09-23 06:45:59

标签: mysql ruby-on-rails ruby random

我的数据库表结构如下

Id  | Name  | Status  | Weight
------------------------------
1   | A     | 1       | 130
2   | A     | 2       | 140
3   | A     | 1       | 130
4   | A     | 1       | 120
5   | A     | 3       | 110
6   | A     | 1       | 100
7   | A     | 2       | 110
8   | A     | 2       | 100
9   | A     | 1       | 140
10  | A     | 2       | 130
11  | A     | 3       | 100
12  | A     | 3       | 110
13  | A     | 1       | 120

我想在我的Rails模型中写一个条件,该条件将获得所有可能的记录集合,其总和weight小于260且status 1

例如总和应小于260且状态为1 ..结果可以是

id为[1,4]的记录,其中权重为130 + 120或[1,6],其中权重为130 + 100等...我想要一个具有这种条件的随机记录

我可以访问像

这样的随机记录
Model.offset(rand(Model.count)).first

但是我想访问获取接受此条件的随机记录...并且可以是单个记录或多个记录

3 个答案:

答案 0 :(得分:0)

Model.where(status: 1).group(:name).having('count(weight) < 260')

答案 1 :(得分:0)

Model.where(status: 1).combination(2).to_a.select{|e| e.sum(&:weight) < 260 }.sample

您可以为不同的组合更改组合参数的值。

答案 2 :(得分:0)

试试这个:

my_records =  Model.where(status: 1).each_cons(2).select{|x,y| x.weight + y.weight < 260}

现在是随机单身:

my_records.sample # return single random record