[ACCEPTED]-What's the idiomatic way to write multi-line ActiveRelation queries?-ruby

Accepted answer
Score: 11

Building on Brian's suggestion, this is 1 much more legible and works well.

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
Score: 0

Breaking up into scopes is a good suggestion. In 3 contrast to another answer I prefer defining 2 complicated scopes as a function instead 1 of messing with lambdas, blocks and precedence rules:

def self.near(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)
end

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

More Related questions