简体   繁体   中英

Ruby on Rails: looping through records, but don't show record from current id

I'm able to search through nearby records based on latitude and longitude from geocoder gem, but how do I not show the record that I'm looking at now?

If I'm in a project show with localhost:3000/project/san-diego (a location San Diego, US), and I do nearby search through

# controller
@project = Project.friendly.find(params[:id])
@nearby = Project.near([@project.latitude, @project.longitude], 50, :order => 'distance')

# view
<% @nearby.each do |n| %>
  <span><%= n.title_name %></span>
<% end %>

How do I not display the current record, but all other records that are nearby?

Using geocoder, you can simply do this:

# controller
@project = Project.friendly.find(params[:id])
@nearby = @project.nearbys(50)

# view
<% @nearby.each do |n| %>
  <span><%= n.title_name %></span>
<% end %>

Notice the nearbys method. This finds other of the same object within the given distance (50 miles). In this case, it will find other Project s.

This method is explained in more detail on the Geocoder docs page: https://github.com/alexreisner/geocoder

You can skip it, as a general solution.

<% @nearby.each do |n| %>
  <% next if n == @project %>
  <span><%= n.title_name %></span>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM