Search code examples
ruby-on-railsrubymongoid

How to remove duplicate countries from the list in Rails?


I use Ruby on Rails 5.2 and Mongoid 7.0

How to remove duplicate countries from the list

@badge = @user.places.all

<%= @badge.each do |badge| %>
  <%= badge.country %><p>
<% end %>

Now result:

France Netherlands Spain Netherlands Netherlands Netherlands Indonesia

I need:

France Netherlands Spain Indonesia


Solution

  • I assume that the badges are different but some of them appear to have the same country. Therefore I think you cannot call unique on the badges but must call it on the list of different countries:

    <% @badge.map(&:country).unique.each do |country| %>
      <p><%= country %></p>
    <% end %>
    

    Depending on your database structure and if you need the whole @badges variable in another place there also might be the option to only load a distinct list of countries from the database:

    @countries = @user.places.distinct.pluck(:country)
    
    <% @countries.each do |country| %>
      <p><%= country %></p>
    <% end %>