bar*_*own 6 ruby ruby-on-rails
我的应用程序中有许多多行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
Run Code Online (Sandbox Code Playgroud)
对我来说感觉有点不对劲.从中返回ActiveRelation对象的块似乎是惯用的,但我还没有看到这种方法.
什么是标准?
bar*_*own 11
在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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4823 次 |
| 最近记录: |