4
我正在開發一個rails應用程序,其中Users
有很多Items
。用戶是geocoded感謝另一個模型,我稱爲Place
依靠寶石地理編碼器寶石。geocoder:距離排序索引
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
在用戶模式,我委託從Place
模型方法能夠直接在用戶級訪問它們。
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
相同的技巧用於在項目層面:
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
現在我想建立在項目,使得它們按距離排序,以當前用戶的索引。我沒有找到設計來執行此設置中的任務。
我試圖做與地理編碼器在User
模型near
方法的代表團和Item
模型,但SQL查詢以下失敗抱怨latitude
和longitude
不是items
表的列。這實際上是正確的,但我希望訪問places
表中的那些。
# 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
我想避免其中兩個用戶和項目被具有用於地理編碼(緯度,經度,地址,等等)的屬性的溶液。
您使用了哪個數據庫? Postgres有一個地理信息模塊,可能有助於解決您的問題。 – dpassage
@dpassage - 我真的在Postgres上。你能否給我提供你提到的模塊的更多信息?這些東西。 – microcosme
幾件事情。有Postgre(http://postgis.refractions.net)爲核心,或標準的Postgres擴展earthdistance(http://www.postgresql.org/docs/9.1/static/earthdistance.html)爲較少的核心。 – dpassage