mardi 22 septembre 2015

Rails Collection of random records

My Database Table Structure is like as follows

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

I would like to write a condition in my Rails model which would get all possible collection of records whose sum of weight is less than 260 and status 1

for eg Total Sum should be less than 260 and status is 1.. the results can be

records with id [1,4] where weight is 130 + 120 or [1,6] where weight is 130 + 100 etc... I want a random record with this condition

I can access a random record like

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

But I want to access get the random records that accepts this condition..and can be a single record or multiple records




Aucun commentaire:

Enregistrer un commentaire