【问题标题】:Rails Collection of random recordsRails 随机记录的集合
【发布时间】:2015-12-20 08:51:49
【问题描述】:

我的数据库表结构如下

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 模型中编写一个条件,它将获取所有可能的记录集合,其总和小于 260 weightstatus 1

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

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

我可以访问随机记录,例如

Model.offset(rand(Model.count)).first

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

【问题讨论】:

    标签: mysql ruby-on-rails ruby random


    【解决方案1】:
    Model.where(status: 1).group(:name).having('count(weight) < 260')
    

    【讨论】:

      【解决方案2】:
      Model.where(status: 1).combination(2).to_a.select{|e| e.sum(&:weight) < 260 }.sample
      

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

      【讨论】:

        【解决方案3】:

        试试这个:

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

        现在是随机单曲:

        my_records.sample # return single random record
        

        【讨论】:

          猜你喜欢
          • 2011-04-08
          • 2014-08-04
          • 2011-07-17
          • 2021-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-08
          相关资源
          最近更新 更多