Rails - PostGIS + postgis_adapter Geometry Problem - ruby-on-rails

I use postgis_adapter alongside with PostgreSQL 9.0.4, PostGIS 1.5.2 and Rails 3.1.0 on Ruby 1.9.2.
As described in the the postgis_adapter README, I tried to perform
Model.create(:geom => Point.from_x_y(10,20))
Postgres responds with
ERROR: parse error - invalid geometry
HINT: You must specify a valid OGC WKT geometry type such as POINT, LINESTRING or POLYGON
The created GeoRuby Object looks like this:
#<GeoRuby::SimpleFeatures::Point:0x0000010420a620 #srid=4326, #with_z=false, #with_m=false, #y=20, #x=10, #z=0.0, #m=0.0>
Hopefully someone got an idea.

Executive summary: it may work if you change it to:
Model.create(:the_name_of_your_geo_column => Point.from_x_y(10,20))
Longer version, with a high probability of Ruby howlers: I've barely written a word of rb but saw one too many great projects this week to continue in a state of ignorance. Working through the error messages in irb (starting from 0 in the language but very familiar with PostGIS):
ActiveRecord::Base.establish_connection(:adapter=>'postgresql',:database=>'moveable')
pt = TablePoint.new(:data => "Hello!",:geom => Point.from_x_y(1,2))
NameError: uninitialized constant Point
So, require 'postgis_adapter', but then:
PGError: ERROR: relation "table_points" does not exist
This must be that awesome naming convention in ActiveRecord that I've heard about. So create a table called table_points because I don't know what the database model/sync methods are.
moveable=> create table table_points(data text, geo_something geometry);
Notice here I used geometry rather than geography because my first instinct as to your problem was that the modeling methods in the database adapter layer created point types. Not at all, actually. Then again in irb,
pt = TablePoint.new(:geom => Point.from_x_y(1,2))
ActiveRecord::UnknownAttributeError: unknown attribute: geom
No attribute named geom? Just to see what would happen, again in psql:
moveable=> alter table table_points add column geom geometry;
ALTER TABLE
Then:
irb(main):014:0> pt = TablePoint.new(:geom => Point.from_x_y(10,20))
=> #<TablePoint data: nil, geo_something: nil, geom: #<GeoRuby::SimpleFeatures::Point:0x1022555f0 #y=20, #with_m=false, #x=10, #m=0.0, #with_z=false, #z=0.0, #srid=-1>>
irb(main):015:0> pt.save
=> true
Unbelievable! What if I did:
pt = TablePoint.new(:data => 'is this even possible?', :geom => Point.from_x_y(38,121), :geo_something => Point.from_x_y(37,120))
=> #<TablePoint data: "is this even possible?", geo_something: #<GeoRuby::SimpleFeatures::Point:0x102041098 #y=120, #with_m=false, #x=37, #m=0.0, #with_z=false, #z=0.0, #srid=-1>, geom: #<GeoRuby::SimpleFeatures::Point:0x1020410c0 #y=121, #with_m=false, #x=38, #m=0.0, #with_z=false, #z=0.0, #srid=-1>>
irb(main):023:0> pt.save
=> true
Even more unbelievable!
moveable=> select * from table_points;
data | geo_something | geom
--------+-----------------+--------
| | 0101000000000
| 010100000000000 |
| 010100000000000 |
...ble? | 00005E400000000 | 010000405E40
(4 rows)
I hesitate to post this as an answer because of fundamental lack of familiarity with Ruby but the above works (mindbendingly, to me), and you may be able to adapt it to your case.

My knowledge of Rails and Ruby is very limited, but try instead:
class Model < ActiveRecord::Base
end
pt = Model.new(:geom => Point.from_x_y(10,20))
pt.save

Adding a Spatial Reference System Identifier (SRID) fixed this problem for me:
Model.create(:geom => Point.from_x_y(10,20, 4326))
If you're using Google Maps, 4326 is the right SRID. Other maps and vendors might use something else.

I ran into a similar problem using spatial_adapter when upgrading a working app from Rails-3.0 to 3.1. It seems newer versions of ActiveRecord type cast your record to a GeoRuby object during insert. The activerecord-postgis-adapter correctly handles the type cast of your geometry column (presumably to EWKT). I spent a lot of time chasing this today and Aaron Patterson's response in this post was very helpful.
To fix your problem, upgrade your Gemfile and database.yml to use activerecord-postgis-adapter.

Related

"no implicit conversion of nil into String"in the Search Module of Redmine

On the redmine of my company, there is this bug where I get an internal error if I want to search into a project.
Here is the log corresponding to the error:
Processing by SearchController#index as HTML
Parameters: {"utf8"=>"✓", "issues"=>"1", "q"=>"test", "id"=>"sprint"}
Current user: me (id=60)
Completed 500 Internal Server Error in 85.0ms
TypeError (no implicit conversion of nil into String):
lib/plugins/acts_as_searchable/lib/acts_as_searchable.rb:126:in `search'
app/controllers/search_controller.rb:74:in `block in index'
app/controllers/search_controller.rb:73:in `each'
app/controllers/search_controller.rb:73:in `index'
The lines corresponding to the error in the controller are :
if !#tokens.empty?
# no more than 5 tokens to search for
#tokens.slice! 5..-1 if #tokens.size > 5
#results = []
#results_by_type = Hash.new {|h,k| h[k] = 0}
limit = 10
#scope.each do |s|
r, c = s.singularize.camelcase.constantize.search(#tokens, projects_to_search,
:all_words => #all_words,
:titles_only => #titles_only,
:limit => (limit+1),
:offset => offset,
:before => params[:previous].nil?)
#results += r
Here is my config :
Environment:
Redmine version 2.6.9.stable
Ruby version 2.3.0-p0 (2015-12-25) [x86_64-linux]
Rails version 3.2.22
Environment production
Database adapter PostgreSQL
SCM:
Git 1.9.1
Filesystem
Redmine plugins:
no plugin installed
What is interesting is that when I search only one letter, i'm redirected on the search page, but I don't have an internal error.
I'm very new to Redmine developpement and to Ruby, I was just assigned to try to fix this bug. Do any of you have an idea of how to fix it ?
Thanks.
I had the same issue, I was able to fix it by downgrading my ruby & rails version, a working set is :
Rails 3.2.19
Ruby 2.1.4p265
It's look like it's due to a braking change in ruby-2.3.0.
It's really odd. We are using 'Redmine' -2.0.3.1 and we do not have that kind of behaviour.
It seems that "someone" messed up the form linked to the search input. Try to follow that data from when you press enter until it answer you with the 500 error code.
If you can , change the environment to development, this way it will show you more detailed errors.
But I can't help you much more , you didn't provide enough info about the problem.

Rails 4.2 syntax error, unexpected ':', expecting =>

I have two computers that I mainly use to develop my Rails application. While working on Computer 1, I added some bootstrap elements to some inputs. For example:
= f.select :transport_from_state, options_for_select(state_populator, #invoice_ambulance.transport_from_state), { include_blank: true}, { class: 'chosen-select', 'data-placeholder': 'State' }
I added the 'data-placeholder': 'State' and used the 'newer' syntax instead of the old :data-placeholder' => 'State' which works fine. The page works with no errors on Computer 1.
I pulled down on computer 2, and now I am getting an error for every instance of 'data-placeholder'. Here is my error:
syntax error, unexpected ':', expecting =>
...en-select', 'data-placeholder': 'State' }
I can replace it with the old syntax and it works fine. However, I shouldn't have to switch 100 instances of this to a deprecated syntax. I have since bundle installed, bundle updated, and rebuilt the db with no luck.
Computer 1 (works)
ruby 2.2.0p0
Rails 4.2.0
Computer 2 (doesnt work)
ruby 2.2.0preview1
Rails 4.2.0
You need to upgrade Computer 2 to the real Ruby 2.2.0 rather than this beta-ish "preview" version you have. Using quoted symbols with the JavaScript-style trailing colon syntax:
{ 'some string': value }
wasn't valid before Ruby 2.2, the 2.2.0preview1 version you have on Computer 2 apparently doesn't support it.
BTW, there is no old and new syntax, there is an alternate JavaScript-style notation that can be use when the keys in a Hash-literal are some symbols. Whoever told you that the hashrocket is deprecated is, at best, confused.
The "newer" syntax is only for symbols.
{hello: 'world'} is equivalent to {:hello => 'world'} but if your key is a string then you still have to use the "hash rocket" syntax: {'hello' => 'world'}
http://ruby-doc.org/core-2.2.0/Hash.html

Postgres throws error when running import from activerecord-import gem

I switched to Postgres in development and now following error breaks a test case:
PG::Error: ERROR: column "id" of relation "assets_content_nodes" does not exist
: SELECT pg_get_serial_sequence($1, $2)
Same error happens in development and production environments but it is not a show stopper and does not affect the import.
assets_content_nodes is a join table and I'd rather not add the 'id' column.
Any ideas why this may be happening?
This is fixed in activerecord-import -v0.3.1 (or possibly an earlier version, but it was broken in 0.2.11 and earlier). You no longer need an id column on a table to do an import.
You might also try Upsert.
If you're importing pets:
require 'csv'
require 'upsert'
u = Upsert.new Pet.connection, Pet.table_name
CSV.foreach('pets.csv', headers: :first_row) do |row|
selector = { name: row['name'] }
setter = row
u.row selector, setter
end
My tests show it's 20–30% faster than activerecord-import. Since it's "upserting," it's generally OK if the process gets interrupted and you just start over from the beginning.

Postgresql WHERE clause adds '' around?

This morning I switched to postgresql and now my where selects dont work anymore.
What I am trying to do is super simple:
shirt_ids = "1,5,6" # String generated by javascript
Shirt.where("id in (?)", shirt_ids)
This gives me :
PG::Error: ERROR: invalid input syntax for integer: "1,5,6"
LINE 1: SELECT "shirts".* FROM "shirts" WHERE (id in ('1,5,6'))
This works though:
Shirt.where("id in (#{shirt_ids})")
But as everybody knows is unsafe.
Im using:
pg (0.13.2 x86-mingw32)
rails (3.2.2)
Postgresql database is the newest version, I installed it this morning.
Thank you for your help.
^
I believe Postgres is expecting an array, rather than a string for the IN function. If you convert your string to an array, it should work:
shirt_ids = "1,5,6"
Shirt.where('id in (?)', shirt_ids.split(','))
Also, you can do this, which looks a bit cleaner:
Shirt.where(:id => shirt_ids.split(','))

How do I fix Stack Overflow after upgrading rails 2.0.2 to 2.3.5 (or even 2.1.0) => in ActiveRecord::SessionStore

Ok, so we're upgrading a client's legacy code from 2.0.2 to latest rails. Most of the basics were easy to fix, but I can't get to the admin screens. Every time we hit "current_user" we get a "stack level too deep" error.
I've dug deeply into the code (read: flailed around a lot at random) and I've finally narrowed it down to the ActiveRecord::Session store.
The code berks out on the line that includes "session[:user]".
When I spool up script/console I can replicate the stack overflow with the following line:
s = ActiveRecord::SessionStore::Session.new(:session_id => '42', :data => {})
stacktrace to follow.
To make sure it wasn't some weird incompatibility, I blew away the session table in the db and reloaded using rake db:sessions:create and it's still asploding on that line.
SystemStackError: stack level too deep
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/schema_definitions.rb:68:in `type_cast'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/dirty.rb:161:in `field_changed?'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/dirty.rb:132:in `write_attribute_without_dirty'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/dirty.rb:139:in `write_attribute'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:211:in `session_id='
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2746:in `send'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2746:in `attributes='
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2742:in `each'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2742:in `attributes='
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2438:in `initialize'
from (irb):10:in `new'
I went into active_record and put in heaps of puts lines. Here's a brief version the final two lines are continually repeated and are clearly the stack-overflow... but why does column_for_attribute(session_id) cause an overflow?
"in respond_to? method: session_id="
"in respond_to? session_id= - there are no generated methods. generating..."
"in respond_to? session_id= - methods generated"
"responds to session_id=? y"
"in respond_to? method: session_id="
"in respond_to? session_id= - super is true"
"in read_attribute: session_id about to fetch value"
"fetched attr value: nil"
"read attr: session_id - value nil"
"column for attribute: session_id"
"c_for_a got col hash - accessing for name: session_id"
"column for attribute: session_id"
"c_for_a got col hash - accessing for name: session_id"
"column for attribute: session_id"
"c_for_a got col hash - accessing for name: session_id"
"column for attribute: session_id"
"c_for_a got col hash - accessing for name: session_id"
Note: we also tried upgrading just to 2.1.0 and the same error occurs (when trying to login - obviously the session-class changed names in between so the scipt/console issue depends on the classname). This time it's endlessly trying just "id" instead of "session_id".
Current environment.rb session settings (for the 2.1.0 version) is below:
# Use the database for sessions instead of the file system
# (create the session table with 'rake db:sessions:create')
config.action_controller.session_store = :active_record_store
config.action_controller.session = { :session_key => "_our_session_id",
:secret=> "some random secret key of your choosing over 30 characters" }
If I drop it back to v2.0.2 it works again.
So I guess the question is: what changed in the ActiveRecord Session between v 2.0.2 and 2.1.0 and how do I make it work?
Ok, looks like the problem was an old back-port/monkey-patch. In the plugins directory we had a back-port of the "dirty" functionality - which I'm guessing must've come out in Rails 2.1.0. All I know is that deleting that plugin seems to have made the "stack level too deep" problem go away (for now). :)

Resources