0

When in the rails console the following code prints to screen an array of coordinates in geojson format as I expect it to:

Bg.
  select("bg_id, ST_AsGeoJSON(the_geom) as my_geo").
  where("ST_Contains(ST_MakeEnvelope(-xxx,xxx,-xxx,xxx, 4269), bg.the_geom)").
  map(&:my_geo)

The select portion however isn't just asking for the json. What if I would also like the bg_id's in the array too?

2 Answers 2

1

What kind of inner data structure are you trying to end up with (i.e. where are you going to put the bg_ids)? E.g. if it's just a hash I think you could change

map(&:my_geo)

to

map{|b| {b.id => b.my_geo} }
Sign up to request clarification or add additional context in comments.

3 Comments

Ultimately what I want is a hash with the bg_id's as the keys and the geojson objects as the values. What you provided here creates an array of hashes. I used .reduce Hash.new, :merge to make a single hash exactly as I would like it. So I guess my question is answered unless you can think of an better way. Thanks!
Also, although this works, I'm not sure I understand why. This looks like it is calling methods called id and my_geo on each item of the array... Is that correct?
Ah, yeah in that case reduce is the way to go. Yes that's correct, it's calling methods. (&:my_geo) is shorthand for {|obj| obj.my_geo}
1

You just need to remove the map and active record objects.

results = Bg.select("bg_id, ST_AsGeoJSON(the_geom) as my_geo").
where("ST_Contains(ST_MakeEnvelope(-xxx,xxx,-xxx,xxx, 4269), bg.the_geom)")

And then:

results[0].bg_id
results[0].my_geo

Or use map if you want an array of something else. Like an array of arrays [[bg_id1,my_geo1],[bg_id2,my_geo2]...]:

results.map{|b| [b.bg_id,b.my_geo] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.