Rails 4 select Uniq

Asked

Viewed 108 times

0

I have the table Items:

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 that does not repeat the class, I am trying so:

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

But it’s not working. Keep returning the repeated.

  • not working out does not help. Show error message or, if any, unexpected result. I do not know Rails but parentheses are not missing? uniq()

1 answer

1

If you don’t need any information beyond the separate fields you can do:

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

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

Or

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

With the pluck are not instantiated objects of type Item, but an array of arrays of type [enrollment_id, turma_id]. In this case Pluck has to be the last method called, so Uniq comes before.

If you need ids or other information other than that are not part of distinct, in Postgresql you can use distinct on:

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

In case you wanted to get the first records guaranteed, you can add order by id.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.