Mysql Rails随机记录的收集
我的数据库表结构如下Mysql Rails随机记录的收集,mysql,ruby-on-rails,ruby,random,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
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
对于eg,总和应小于260,状态为1。。结果可能是
id为[1,4]且重量为130+120或[1,6]且重量为130+100等的记录。。。我想要一个有这种条件的随机记录
我可以访问像这样的随机记录
Model.offset(rand(Model.count)).first
但我想访问获取接受此条件的随机记录..可以是单个记录或多个记录Model.where(状态:1).group(:name).having('count(weight)<260'))
Model.where(status: 1).group(:name).having('count(weight) < 260')
型号.位置(状态:1).组合(2).选择{e | e.sum(&:weight)<260}.样本
您可以更改不同组合的组合参数值。尝试以下操作:
my_records = Model.where(status: 1).each_cons(2).select{|x,y| x.weight + y.weight < 260}
my_records = Model.where(status: 1).each_cons(2).select{|x,y| x.weight + y.weight < 260}
my_records.sample # return single random record