加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 编写多行ActiveRelation查询的惯用方法是什么

发布时间:2020-12-16 23:28:03 所属栏目:百科 来源:网络整理
导读:我的应用程序中有许多多行ActiveRelation查询方法,我不确定编写这些方法的最惯用方法.看看这个例子: def postal_code_ids_within(miles) nearby_postal_codes = PostalCode.where("latitude :min_lat and latitude :max_lat",min_lat: (latitude - (miles.t
我的应用程序中有许多多行ActiveRelation查询方法,我不确定编写这些方法的最惯用方法.看看这个例子:
def postal_code_ids_within(miles)
  nearby_postal_codes = PostalCode.where("latitude > :min_lat and latitude < :max_lat",min_lat: (latitude - (miles.to_f / MILES_PER_DEGREE_LATITUDE.to_f / 2.to_f)),max_lat: (latitude + (miles.to_f / MILES_PER_DEGREE_LATITUDE.to_f / 2.to_f)))
  nearby_postal_codes = nearby_postal_codes.where("longitude > :min_lon and longitude < :max_lon",min_lon: (longitude - (miles.to_f / MILES_PER_DEGREE_LONGITUDE.to_f / 2.to_f)),max_lon: (longitude + (miles.to_f / MILES_PER_DEGREE_LONGITUDE.to_f / 2.to_f)))
  nearby_postal_codes.pluck(:id)
end

对我来说感觉有点不对劲.从中返回ActiveRelation对象的块似乎是惯用的,但我还没有看到这种方法.

什么是标准?

解决方法

在Brian的建议的基础上,这更加清晰,效果也很好.
scope :near,lambda { |postal_code,miles|
  degree_offset = miles / MILES_PER_DEGREE / 2
  where("latitude > :min_lat and latitude < :max_lat and longitude > :min_lon and longitude < :max_lon",min_lat: postal_code.latitude - degree_offset,max_lat: postal_code.latitude + degree_offset,min_lon: postal_code.longitude - degree_offset,max_lon: postal_code.longitude + degree_offset)
}

def postal_code_ids_within(miles)
  self.class.near(self,miles).pluck(:id)
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读