PG::SyntaxError at / ERROR: syntax error at or nea

2019-09-07 03:17发布

问题:

I am getting this error some time and some time not. That is strange.

ERROR: syntax error at or near ")" LINE 1: SELECT locations.*, () as distance FROM "locations" ORDER ...

In line

nearby_locations.includes(:events).each do |location|

In my Dashboard controller

 def home            
    nearby_locations = Location.with_distance_to(remote_ip).order('distance').limit(10)
    @events  = []
    nearby_locations.includes(:events).each do |location|
        @events += location.events.where("publish = true")
    end
end

In my Location.rb model

geocoded_by :address
extend Geocoder::Model::ActiveRecord
  reverse_geocoded_by :latitude, :longitude

  scope :with_distance_to, ->(point) { select("#{table_name}.*").select("(#{distance_from_sql(point)}) as distance") }

回答1:

To stop the errors, you should validate that remote_ip in your dashboard_controller exists before using the scope you have defined on Location.

 def home            
  unless remote_ip.blank?
    nearby_locations = Location.with_distance_to(remote_ip).order('distance').limit(10)
    @events  = []
    nearby_locations.includes(:events).each do |location|
        @events += location.events.where("publish = true")
    end
  end
end

To really understand the problem, find out how remote_ip is blank in the first place and fix that issue.