简体   繁体   中英

Rails 3 gem 'geocoder' search functionality and model design

I have a sort of general question about the geocoder gem and how to design my models in rails to facilitate the useful features of the geocoder.

I have an Article model, and Place model. An Article will always be written about a Place, so an article will always have a place_id. The Place model contains the address of the place and and the :latitude and :longitude columns that geocoder requires.

geocoder has a method 'nearbys' that allows me to find places nearby a given place, for example @place.nearbys would yield a collection of places nearby @place. That's great, but I want to be able to find all the articles that are written recently, and written about places nearby.

I can only think of two ways to do that. Either add a latitude and longitude column to my Article model, which would allow me to search @articles.nearby. The problem with this solution is that it seems like it wouldn't be good model design, since a Place should be responsible for holding the latitude and longitude, not every article written about the place.

If you can make some suggestions on how I could easily achieve this, that would be great, thatnks!

couple of options that might work for you?

@places = Place.near(@search, @distance, :order => :distance)
@articles = Article.where("place_id IN (?)", @places).where("published_on > ?", 60.days.ago).limit(3 * @places.length)

lazy load the articles from the places but limit the results

@place = Place.find(params[:id])
@place.nearbys(@distance).each do |place|
    place.articles.order("created_at desc").limit(3).each do |article|
        # ...
    end
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