【问题标题】:is there a more elegant way to write this in ruby?有没有更优雅的方式用红宝石写这个?
【发布时间】:2011-08-04 23:19:27
【问题描述】:
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)

不是说这很可怕,但我想知道是否有更好的方法?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord


    【解决方案1】:

    实际上你想要的是一个装订盒,它需要四个角。所以其他的写法可以是:

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-05-22
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多