Majoris
Majoris

Reputation: 3189

Ruby rails - select only few columns from the database

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;

Upvotes: 67

Views: 88884

Answers (6)

eriel marimon
eriel marimon

Reputation: 1380

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`
 => ["[email protected]", "[email protected]"] 

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

Upvotes: 8

dku.rajkumar
dku.rajkumar

Reputation: 18568

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 => { .... } )

Upvotes: 30

Michelle Tilley
Michelle Tilley

Reputation: 159105

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 => ...

Upvotes: 11

Kuberan
Kuberan

Reputation: 141

@itemlist = Item.select('name, address').where(...#some condition)

Upvotes: 7

nyaa
nyaa

Reputation: 1736

Rails 3:

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

Upvotes: 134

coder_tim
coder_tim

Reputation: 1720

Try this:

@itemlist = Item.find(:all, :select => "name, address", :conditions => { .... } )

Upvotes: 3

Related Questions