Ruby on Rails Active Record Query (.each, .collect, .map ...?) Ruby on Rails Active Record Query (.each, .collect, .map ...?) sqlite sqlite

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


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

Market.pluck(:zipcode)


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.