18

Not sure why I can't find out how to do this easily... Obviously I could do it with raw SQL, but I'm trying to familiarize myself with ActiveRecord.

results = Model.where(:lat => (south..north), :lng => (east..west))

I don't want all the fields, just a few. How would I limit the results to only include columns I choose?

Patm
  • 2,045
  • 4
  • 19
  • 22

3 Answers3

32
results = Model.where(:lat => (south..north), :lng => (east..west)).select([:lat, :long, :id])

You'll also probably want to include the :id in that select if you want your results to behave like reasonable ActiveRecord objects.

Edit: Select takes a single arg, can be an array.

Ray Baxter
  • 3,181
  • 23
  • 27
  • Thanks. One correction to your code above is what unixcharles said in his answer: argument for select needs to be an array of the fields or sql string. – Patm Jul 11 '11 at 18:38
4

You need to use select

Model.where(...).select(...)

select accept array or raw sql string.

http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

Charles Barbier
  • 835
  • 6
  • 15
0

Technically, if you want to reuse the data subset filter for readonly models, you can create a 'view' at the database level. See http://dev.mysql.com/doc/refman/5.0/en/views.html

Ivar
  • 5,102
  • 2
  • 31
  • 43