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.
I would like to avoid a solution when both users and elements have attributes for geocoding (latitude, longitude, address, etc.).