Search code examples
ruby-on-railsrubyactiverecordspatialite

ActiveRecord set field to SQL expression


I am using Ruby 1.8.7 and Rails 2.3.8 and have a number of locations represented by a latitude and a longitude. I am using the SQLite SpatiaLite extension to convert the coordinates to the well-known binary (WKB) format. My concern is how to have ActiveRecord perform the insert or update, calling the appropriate SpatiaLite conversion methods. I am looking to do something like this:

obj.geometry = "AsBinary(MakePoint(4, 51))"
obj.save
# ActiveRecord would now do something like:
# INSERT INTO objects (geometry) VALUES (AsBinary(MakePoint(4, 51)))

Is this possible with ActiveRecord?

I have already tried GeoRuby but while its able to properly read WKB blobs, it is unable to save them to the same format SpatiaLite does.

Thanks!


Solution

  • After days of searching and coming up with no solution, I decided to simply leverage the raw connection to perform the actual insert:

    rc = ActiveRecord::Base.connection.raw_connection
    rc.execute("INSERT INTO objects (geometry)
                VALUES (MakePoint(#{obj.lng}, #{obj.lat}))")