Get Unique records per attribute in Active Record

859 Views Asked by At

I have Student model and I would like to get one record per term_id (one of the attributes).

Student.select(:term_id).distinct 

works but the result is an array of term_ids, not the objects themselves - which is what I would like to get

2

There are 2 best solutions below

6
On

Try this:

Student.pluck("DISTINCT id, term_id")
2
On
Student.select("DISTINCT term_id, `students`.* ")

Incase if you are using older versions of ruby (< 2.3.8),

Student.find(:all, :select => "DISTINCT(term_id), `students`.*")

or if you want id alone,

Student.find(:all, :select => "DISTINCT(term_id), id")

where students is your table name. You will get array of objects.