Archer
Archer

Reputation: 1124

Rails shuffle with priority

I've got a model with some records with an own priority.

  1. Record => priority: 1
  2. Record => priority: 2
  3. Record => priority: 3
  4. Record => priority: 3
  5. Record => priority: 2
  6. Record => priority: 1
  7. Record => priority: 1
  8. Record => priority: 4

Now I need a random record based on it's priority. Priority 1 is the worst. Priority 4 is the best.

Now I get just a random record with @records.all.shuffle What is the best way to combine it with it's priority?

Upvotes: 0

Views: 84

Answers (1)

Daniil Maksimov
Daniil Maksimov

Reputation: 139

Perhaps you need something like:

max_priority = Record.maximum(:priority)
Record.where(priority: max_priority).all.shuffle

Postgresql way:

Record.order('priority DESC, RANDOM()').first

Upvotes: 1

Related Questions