Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving only certain columns with Rails 3 where clause

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?

like image 772
Patm Avatar asked Jul 11 '11 18:07

Patm


2 Answers

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.

like image 104
Ray Baxter Avatar answered Oct 12 '22 03:10

Ray Baxter


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

like image 43
Charles Barbier Avatar answered Oct 12 '22 02:10

Charles Barbier