Rails 4 select Uniq

0

I have the Items table:

id   enrollment_id   turma_id
11   2               2
12   2               3
13   2               2
14   2               2
15   2               3    

I want my result to be this:

id   enrollment_id   turma_id
11   2               2
12   2               3  

That is, I want all the items, but do not repeat the class, I'm trying like this:

@itens = Item.where(turma_id: @turma.id).uniq

But it is not working. It keeps returning the repeats.

    
asked by anonymous 18.11.2014 / 18:21

1 answer

1

If you do not need any information besides the distinct fields you can do:

@itens = Item.select(:enrollment_id, :turma_id).uniq

In this case, objects of type Item are instantiated with id equal to nil .

Or

@itens = Item.uniq.pluck(:enrollment_id, :turma_id)

With pluck objects of type type are not instantiated, but rather an array of arrays of type [enrollment_id, turma_id]. In that case the pluck has to be the last method called, so uniq comes first.

If you need the ids or other information besides that are not part of the distinct, in PostgreSQL you can use distinct on :

@itens = Item.select('distinct on (enrollment_id, turma_id) *')

If you wanted to be sure to get the first records, you can add order to the id.

    
19.11.2014 / 12:07