Question

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!

Was it helpful?

Solution

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

Market.pluck(:zipcode)

OTHER TIPS

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.

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

Market.all.map(&:zipcode)

Use Benchmark to determine which is better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top