class Geolocation < ActiveRecord::Base
scope :lat_greater_than_or_equal_to, lambda { |lat| where("latitude >= ?", lat) }
scope :lat_less_than_or_equal_to, lambda { |lat| where("latitude <= ?", lat) }
scope :lng_greater_than_or_equal_to, lambda { |lng| where("longitude >= ?", lng) }
scope :lng_less_than_or_equal_to, lambda { |lng| where("longitude <= ?", lng) }
end
因此,我正在做:
Geolocation.lat_greater_than_or_equal_to(lat_min).
lat_less_than_or_equal_to(lat_max).
lng_greater_than_or_equal_to(lng_min).
lng_less_than_or_equal_to(lng_max)
这不是可怕的,但我想知道是否有更好的方式?
答案 0 :(得分:3)
实际上你想要的是一个绑定盒,它需要四个角。所以编写它的其他方式可以是:
class Geolocation < ActiveRecord::Base
scope :binding_box, lambda { |lat_min, lng_max, lat_max, lng_min| where(
"latitude >= ? AND latitude <= ? AND longitude >= ? AND longitude <= ?",
lat_min, lat_max, lng_min, lng_max
)}
end
Geolocation.binding_box(lat_min, lng_max, lat_max, lng_min)