Geocoder: distance-sortable index

I am developing a rails application where Users have many Items . Users are geocoded thanks to another model, which I called Place , which relies on a gem of a ruby โ€‹โ€‹geocode.

 class Place < ActiveRecord::Base attr_accessible :street_number, :street, :city, :postal_code, :country, :latitude, :longitude belongs_to :placable, :polymorphic => true geocoded_by :address after_validation :geocode def address [street_number, street, postal_code, city, country].compact.join(', ') end end 

In the user model, I delegated methods from the Place model to access them directly at the user level.

 class User < ActiveRecord::Base has_many :items, :dependent => :destroy has_one :place, :as => :placable, :dependent => :destroy accepts_nested_attributes_for :place attr_accessible :place_attributes geocoded_by :address delegate :address, :to => :place, :allow_nil => true delegate :latitude, :to => :place, :allow_nil => true delegate :longitude, :to => :place, :allow_nil => true #... end 

The same trick is used at the element level:

 class Item < ActiveRecord::Base belongs_to :user # place geocoded_by :address delegate :place, :to => :user, :allow_nil => true delegate :address, :to => :user, :allow_nil => true delegate :latitude, :to => :user, :allow_nil => true delegate :longitude, :to => :user, :allow_nil => true # ... end 

Now I would like to set up an index for such items so that they are sorted by distance from the current user. I did not find a design to complete the task in this setting.

I tried the following with delegating the near method from geocoding in the User model and the Item model, but the sql query does not respond that latitude and longitude are not columns in the Items table. This is really correct, but I want to access them in the places table.

  # this added to the user model: delegate :near :to => :place # this added to the item model: delegate :near :to => :user class ItemsController < ApplicationController def index @items=Item.near(current_user.place, params[:distance]).paginate(:per_page => 20, :page => params[:page_name]) end end 

I would like to avoid a solution when both users and elements have attributes for geocoding (latitude, longitude, address, etc.).

+4
source share
1 answer

I donโ€™t know if this is too much for me, or am I mistaken, but let me try:

I would simply create a column (e.g. location - in the Item model) to save the current location of the item and then compare it with the user's current location.

Not what you were looking for? hope i helped!

0
source

Source: https://habr.com/ru/post/1442402/


All Articles