64

What is the way in Rails to structure SQL query to only select certain columns from the database, I have some large data fields which I want to avoid loading from continuous periodic Ajax calls. Reading unnecessarily is resource consuming and slow.

@itemlist = Item.find(:all, :conditions => { .... } ) #this select all columns 

I am looking for SELECT name, address FROM users; instead of SELECT * FROM users;

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
Majoris
  • 2,963
  • 6
  • 47
  • 81

6 Answers6

131

Rails 3:

Item.select("name, address").where( .... )

nyaa
  • 1,706
  • 2
  • 11
  • 7
  • Yup, great one! Promote this one, guys, as Rails 3 is far more popular than the 2nd one – Jackie Chan Apr 13 '13 at 13:07
  • 2
    Also of note, if you have more than one table in your `SELECT` statement and you're referencing a column that could exist in more than 1 table, include the table in the select, like `select("items.name, users.address")`. – Joshua Pinter Aug 27 '14 at 16:39
  • Still works in Rails 7. – B Seven May 09 '23 at 14:35
30

Make use of :select construct. Try this:

@itemlist = Item.select('name, address', conditions: { .... } )

For previous version of Rails:

@itemlist = Item.find(:all,:select => 'name, address', :conditions => { .... } )
pranavcode
  • 747
  • 4
  • 12
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
11

Using Arel (aka in Rails 3), use:

Item.where(...).select("name, address")

Also, it seems .select gets ignored if you tack on a scope that has an :include => ...

Simon B.
  • 2,530
  • 24
  • 30
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
7
@itemlist = Item.select('name, address').where(...#some condition)
Kuberan
  • 141
  • 8
7

If want to select specific columns from the rails console, pluck( will work. Example:

2.4.1 :007 > User.connection
2.4.1 :006 > User.all.pluck(:email)
   (0.3ms)  SELECT `users`.`email` FROM `users`
 => ["test@test.com", "another_test@test.com"] 

Note that this will also work from within the Rails app.

eriel marimon
  • 1,230
  • 1
  • 19
  • 29
3

Try this:

@itemlist = Item.find(:all, :select => "name, address", :conditions => { .... } )
coder_tim
  • 1,710
  • 1
  • 12
  • 13