好的,我有一个卡车装载板,卡车司机可以在那里张贴可用的卡车。我有卡车张贴。但是在设置搜索功能以及我需要关联不同表的方式时遇到问题。
Rails 3
postgres
gem 'geokit-rails'
我现在拥有的方式是我有一个位置表设置,例如:
class Location < ActiveRecord::Base
attr_accessible :cs, :lat, :lon, :city, :state
acts_as_mappable :default_units => :miles,
:default_formula => :sphere,
:distance_field_name => :distance,
:lat_column_name => :lat,
:lng_column_name => :lon
当有人发布卡车时,它具有起点和终点。所以它有 2 个位置,并且设置如下:
class Truck < ActiveRecord::Base
attr_accessible :available, :company_id, :dest_id, :origin_id, :equipment, :origin, :dest
belongs_to :origin, class_name: "Location", foreign_key: :origin_id
belongs_to :dest, class_name: "Location", foreign_key: :dest_id
belongs_to :company
通过我设置它的方式,我可以从以下位置获取位置信息:
Truck.find(1).origin || Truck.find(1).dest
它将返回与其关联的位置记录
现在我的问题是我希望能够编写一个搜索函数来查找距离原点“给定”英里数内的任何卡车|| 目的地 || 出发地和目的地
我知道我能做到Location.within(25, :origin => "Springfield, Mo")
,它会搜索所有位置并返回 Springfield Mo 25 英里范围内的位置
但是我将如何在有 2 个位置(起点和终点)并且它们与位置 ID 相关联的卡车上使用它。
我目前有一些其他搜索参数已经编码并且正在工作,只是不确定如何将其合并到其中:
def search(search)
where = []
where << PrepareSearch.states('dest', search.dest_states) unless search.dest_states.blank?
where << PrepareSearch.states('origin', search.origin_states) unless search.origin_states.blank?
where << PrepareSearch.location('origin', search.origin_id, search.radius) unless search.origin.blank?
where << PrepareSearch.location('dest', search.dest_id, search.radius) unless search.dest.blank?
where << PrepareSearch.equipment(search.equipment) unless search.equipment.blank?
where << PrepareSearch.date('available', search.available, '<') unless search.available.blank?
where = where.join(' AND ')
Truck.where(where)
end
module PrepareSearch
def PrepareSearch.location(type, location, radius)
loc = Location.find(location)
*type will be origin/destination Location active record
*location will be Location id
*radius will be a given mileage
**This is where i need to figure out what to put here**
end
end
将方程式合并起来会更好:
def sphere_distance_sql(origin, units)
lat = deg2rad(origin.lat)
lng = deg2rad(origin.lng)
multiplier = 3963.1899999999996 # for miles
sphere_distance_sql(lat, lng, multiplier)
end
def sphere_distance_sql(lat, lng, multiplier)
%|
(ACOS(least(1,COS(#{lat})*COS(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*COS(RADIANS(#{qualified_lng_column_name}))+
COS(#{lat})*SIN(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*SIN(RADIANS(#{qualified_lng_column_name}))+
SIN(#{lat})*SIN(RADIANS(#{qualified_lat_column_name}))))*#{multiplier})
|
end