1

I have a model teststep which has the attributes sequence and revision. The attribute revision contains an increased number for every record with the same sequence, like this:

id: 1, sequence: 1, revision: 1
id: 2, sequence: 2, revision: 1
id: 3, sequence: 2, revision: 2
id: 4, sequence: 2, revision: 3

How can I get the records with all different sequence's, but only the highest revision, in this case records with id 1 and 4? I tried something with distinct, but that doesn't work.

John
  • 6,404
  • 14
  • 54
  • 106
  • Have a look over the following post. [https://stackoverflow.com/questions/4222421/with-activerecord-how-can-i-select-records-based-on-the-highest-value-of-a-field](https://stackoverflow.com/questions/4222421/with-activerecord-how-can-i-select-records-based-on-the-highest-value-of-a-field) – Sambit Aug 28 '17 at 12:59

2 Answers2

2

This code should do the trick

TestStep.group(:sequence).pluck(:id, :sequence, 'MAX(revision)')
Bustikiller
  • 2,423
  • 2
  • 16
  • 34
2

try this

Teststep.group(:sequence).having('Max(revision) >= revision')
widjajayd
  • 6,090
  • 4
  • 30
  • 41
  • This: `teststeps.where(teststep_type: "XTestStep").group(:sequence, :id).having('max(revision) >= revision').order(:sequence)` still shows all records, is that because of the extra `where` on `teststep_type`? – John Aug 28 '17 at 12:22
  • I did researched for your last question, it should work although you combined where, group and having, here is some of more information that probably can help you http://findnerd.com/list/view/Group-By-With-Where-Or-Having-clause-in-Rails/2680/ – widjajayd Aug 28 '17 at 12:45