Carrein
Carrein

Reputation: 3361

Setting up Geocoder with Sinatra and ActiveRecord?

I have a MYSQL database which is accessed using ActiveRecord and Sinatra. I am trying to perform certain geolocation task on the records in the tables.

However, i believe my syntax is wrong as extending the geocoder class makes my CRUD request fail:

myapp.rb

require 'rubygems'
require 'sinatra'
require 'active_record'
require 'table_print'
require 'json'

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql2",
  :host     => "localhost",
  :username => "root",
  :database => "orbital"
)

class Post < ActiveRecord::Base
  extend Geocoder::Model::ActiveRecord

 # attr_accessor :latitude, :longitude
end

class Comment < ActiveRecord::Base
  #extend Geocoder::Model::ActiveRecord
end

class MyApp < Sinatra::Application
  #extend Geocoder::Model::ActiveRecord
end

post '/post' do
  @user = params[:user]
  @content = params[:content]
  @latitude = params[:latitude]
  @longitude = params[:longitude]
  @timestamp = params[:timestamp]
  record = Post.create(user: @user, content: @content, longitude: @longitude, latitude: @latitude, timestamp: @timestamp)
  record.save
end

The query I am trying to perform is: Post.near([@lat, @long], @dist, units: :km).offset(10 * @var.to_i).first(10)

This stackoverflow thread here also suggests that I need to setup additional arguments such as attr_accessors. How do I go about setting up rewriting the above so i can use Geocoder's near method?

Upvotes: 1

Views: 88

Answers (1)

Carrein
Carrein

Reputation: 3361

I fixed the above by adding:

require 'geocoder'

and

reverse_geocoded_by :latitude, :longitude

Upvotes: 1

Related Questions