user1596316 user1596316 - 2 months ago 7
Ruby Question

Rails - Use self column in sql string query in concern scope

So, I have this concern and scope

module GeocoordinatesHelpers
extend ActiveSupport::Concern

included do
scope :within_range, -> (lat, lon, range) { where("(6371.0 * 2 * ASIN(SQRT(POWER(SIN((self.latitude - :lat) * PI() / 180 / 2), 2) + COS(self.latitude * PI() / 180) * COS(:lat * PI() / 180) * POWER(SIN((self.longitude - :lon) * PI() / 180 / 2), 2)))) <= :range", {lat: lat, lon: lon, range: range})}
end
end


that I need to use across several models

Is it possible to refer to the models column that the scope is being called against? Like, replace the
self
bits in the where with something that actually works

For reasons, I can't just use the geocoder gem

Answer

If you really need the full column name, try changing self to #{table_name}.

Comments