如果Rails中的相同项目排除

时间:2010-11-26 08:33:42

标签: ruby-on-rails

在我的Shop(姓名= ABC; ID = 10)节目视图中,我想展示附近的商店。因此,我用这个:

          <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 %>

您会注意到h1实际上显示了当前的商店ABC,其余的each实际上显示了它附近的所有商店。问题是,它还包括商店ABC,因为它是最近的点。如何让each排除商店ABC?

2 个答案:

答案 0 :(得分:9)

使用reject

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

然后迭代other_shops

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

答案 1 :(得分:1)

首先设置@shops时,请使用额外条件"id <> ?", shop.id