Tiamon
Tiamon

Reputation: 237

Get Unique records per attribute in Active Record

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

Upvotes: 1

Views: 856

Answers (2)

BinaryMee
BinaryMee

Reputation: 2142

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.

Upvotes: 0

Prashant4224
Prashant4224

Reputation: 1601

Try this:

Student.pluck("DISTINCT id, term_id")

Upvotes: 1

Related Questions