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

This is one example of a single 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 43 zipcodes from all the records in my database. Why are these queries not working?

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

Thanks!

+7
source share
2 answers

If all you need is an array of zip codes, I would suggest trying the following:

 Market.pluck(:zipcode) 
+21
source

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

 Market.all.map(&:zipcode) 

Use Benchmark to determine which is better.

+3
source

All Articles