Nick McD.
Nick McD.

Reputation: 137

How can I assign an variable to an active record object?

The following code will query my db with the ST_AsGeoJSON postgis function and print the json object to the screen when in the rails console.

Zcta.
  select("ST_AsGeoJSON(ST_simplify(geom,500)) as my_geo").
  where(geoid10: '90210').each do |result|
    puts result.my_geo
  end

What if I wanted to put that content in a variable (or array, or hash for that matter)? If i change puts result.my_geo to variable = result.my_geo and then try to use the variable later I get an error saying that the variable doesn't exist.

Any thoughts?

Upvotes: 2

Views: 1222

Answers (3)

acoffman
acoffman

Reputation: 708

You're looking for map instead of each

each will iterate over each item in your Enumerable and execute the block for it, returning nil. In your example, the puts is printing the object out to the console, but its not storing it anywhere.

map, on the other hand will execute the block for each element of the enumerable and return to you a new enumerable containing the result of running the given block on each element.

x = [1,2,3].map { |elem| elem + 1 }
puts x
[2,3,4]

In your case, you could do the following:

result = Zcta.select("ST_AsGeoJSON(ST_simplify(geom,500)) as my_geo")
  .where(geoid10: '90210')
  .map(&:my_geo)

The result of your query will now be stored as an Enumerable in the variable result

Upvotes: 2

ichigolas
ichigolas

Reputation: 7725

Or use map instead:

variable = Zcta.
  select("ST_AsGeoJSON(ST_simplify(geom,500)) as my_geo").
  where(geoid10: '90210').map do |result|
    result.my_geo
  end

Upvotes: 2

Headshota
Headshota

Reputation: 21449

Do you define your variable in the block? Then it won't be accessible outside. define the variable outside of the block first.

Upvotes: 3

Related Questions