A
A
Anton2016-10-17 19:45:29
Ruby on Rails
Anton, 2016-10-17 19:45:29

How to display only unique records of the last connection?

There are two models and their relationships:
Model1 -> belongs to -> Model2
Model2 -> has many -> Model1
On the page, I list the elements of the Model2 model.
Everything is fine, but here's how to remove duplicate lines?
.uniqdoes not help here, since it can only be hung on Model1 in front of.each

Model1.all.each do |item|
  item.model2.name # Иногда выводятся одинаковые имена. Надо оставить только одно уникальное имя.
end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Gladyshev, 2016-10-18
@fairoj

Wouldn't it be easier to do it the other way around?

Model2.joins(:model1).each do |item|
  item.name
end

A
Andrey Sidorov, 2016-10-19
@morr

If the question is about how to make uniq for a collection then
or
If it’s about how to make a selection at all, then it’s better to use the option from fairoj above

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question