简体   繁体   中英

Creating an array from activerecord objects

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?

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

map(&:my_geo)

to

map{|b| {b.id => b.my_geo} }

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] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM