【发布时间】:2012-10-26 20:17:24
【问题描述】:
我正在开发一个 Rails 应用程序,其中 Users 有很多 Items。由于我称为 Place 的另一个模型依赖于 ruby 地理编码器 gem,因此对用户进行了地理编码。
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 模型和Itemmodel 的地理编码器的near 方法的委托执行以下操作,但sql 查询失败,抱怨latitude 和longitude 不是items 表。这实际上是正确的,但我希望访问 placestable 中的那些。
# 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 - 我确实在 Postgres 上。你能给我更多关于你提到的模块的信息吗?谢谢
-
几件事。 PostGIS (postgis.refractions.net) 用于硬核,或标准 Postgres 扩展 earthdistance (postgresql.org/docs/9.1/static/earthdistance.html) 用于不太硬核。
标签: ruby-on-rails oop geocoding rails-geocoder