Victor
Victor

Reputation: 13368

Exclude if same item in Rails

In my Shop (name = ABC; ID = 10) show view, I want to show the nearby shops. Hence, I use this:

          <h1>
            Shops nearby <span id="title"><%=h @shop.name %></span>
          </h1>

<% @shops.each_with_index do |shop, i| %>
                    <% if shop.geocoded? %>
                    {
                      latitude: <%= shop.lat %>,
                    longitude: <%= shop.lng %>,
                      html: "<a href='#item_<%= i + 1 %>'><strong><%=h shop.name %></strong></a>",
                      icon: { image: "<%= APP_CONFIG[:site_url] + '/images/map_blue_' + (i+1).to_s + '.png' %>",
                              iconsize: [48, 48],
                              iconanchor: [24,48],
                              infowindowanchor: [24, 0] }
                    },
                    <% end %>
                  <% end %>

You will notice that the h1 actually shows the current shop ABC, and the rest of each actually shows all the shops nearby it. The problem is, it also includes the shop ABC as it is the nearest point. How do I ask the each to exclude shop ABC?

Upvotes: 3

Views: 731

Answers (2)

Max Williams
Max Williams

Reputation: 32933

When you set @shops in the first place, use an extra condition "id <> ?", shop.id

Upvotes: 2

Jacob Relkin
Jacob Relkin

Reputation: 163228

Use reject:

other_shops = @shops.reject {|shop| shop == @shop}

Then iterate over other_shops:

other_shops.each_with_index do |shop, i|
  ...

Upvotes: 10

Related Questions