代码之家  ›  专栏  ›  技术社区  ›  Victor

排除Rails中的相同项

  •  2
  • Victor  · 技术社区  · 15 年前

    在我的 Shop (name=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,因为它是最近的点。我该怎么问 每个 排除ABC店?

    2 回复  |  直到 15 年前
        1
  •  9
  •   Jacob Relkin    15 年前

    使用 reject :

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

    然后迭代 other_shops :

    other_shops.each_with_index do |shop, i|
      ...
    
        2
  •  1
  •   Max Williams    15 年前

    当你把商店放在第一位时,使用一个额外的条件 "id <> ?", shop.id