Ruby on Rails Active Record Query (.each, .collect, .map ...?)
Asked Answered
B

3

13

This is one example of one entry in my database:

Market id: 1, name: "Independence Park (Independently Run Farmers Market...", address: "3945 N. Springfield Ave., Chicago, IL", zipcode: "60618", created_at: "2013-01-01 21:22:24", updated_at: "2013-01-01 21:22:24"

All I want to do is list the 43 zipcodes from all the entries in my database. Why don't these queries work?

  1. Market.all.each { |m| m.zipcode }
  2. Market.all.zipcode
    • m = Market.all
    • m.each{ |m| m.zipcode }

Thanks!

Booted answered 3/1, 2013 at 16:32 Comment(2)
what is the relation is zip code is feld of market or in relationPoisson
I figured it out...Market.pluck(:zipcode)Booted
B
30

If all you want is an array of zip codes, I would suggest to try this:

Market.pluck(:zipcode)
Barbabas answered 3/1, 2013 at 16:39 Comment(0)
O
5

The other answers have pointed out the correct way to do what you want, but haven't explained why your other attempts didn't work (which is technically the question you asked).

The reason attempts 1 and 3 don't work is that each doesn't return anything, it's only use is to loop through a set of records and perform an action on them (such as updating them or using some data to call an external service). Replacing each with map would fix them, as map uses the return value of the block to return an array of values. This has a disadvantage in that map is an Array method, so all of your records will have to be loaded into memory before the values can be found.

Attempt 2 doesn't work as you're trying to call a field name on an ActiveRecord::Relation (all), so you'll end up raising a NoMethodError.

The neatest solution, and one that has already been pointed out, is to use pluck, which not only returns all the values for the requested fields, but does so at the database query level, so you call should be more efficient.

Osuna answered 5/4, 2021 at 8:53 Comment(0)
T
0

You could also do the following, it returns an array of zipcodes:

Market.all.map(&:zipcode)

Use Benchmark to determine which is better.

Track answered 3/1, 2013 at 17:1 Comment(1)
this will potentially eat loads of ram.Renferd

© 2022 - 2024 — McMap. All rights reserved.