0

I am using Mongoid Spacial to store coordinates on a Place model. I am geocoding on the client side, and sending two text fields: latitude and longitude. The fields are named correctly, and this appears to be a server-side issue because the coordinates fail silently to persist in the Rails console as well.

Model

class Place
  include Mongoid::Document
  include Mongoid::Paranoia
  include Mongoid::Timestamps
  include Mongoid::Spacial::Document

  attr_accessible :coordinates, :latitude, :longitude

  field :coordinates, type: Array, spacial: true

  spacial_index :coordinates

  def latitude
    coordinates[:lat]
  end

  def latitude=(latitude)
    self.coordinates[:lat] = latitude
  end

  def longitude
    coordinates[:lng]
  end

  def longitude=(longitude)
    self.coordinates[:lng] = longitude
  end
end

I understand that the coordinates field is an array, and that it returns as an object.

I can successfully set the coordinates using the following command:

self.coordinates = [-98.765432,12.345678]

But not with these commands:

self.coordinates[:lng] = -98.765432

self.coordinates[0] = -98.765432

How can I write the setter to make this work?

Micah Alcorn
  • 2,363
  • 2
  • 22
  • 45

1 Answers1

0

Here is a working solution, but there is surely a better way to do this.

  def latitude
    coordinates[:lat]
  end

  def latitude=(lat)
    self.coordinates = [self.longitude,lat]
  end

  def longitude
    coordinates[:lng]
  end

  def longitude=(lng)
    self.coordinates = [lng,self.latitude]
  end
Micah Alcorn
  • 2,363
  • 2
  • 22
  • 45