Reputation: 3189
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
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
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
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
Reputation: 1720
Try this:
@itemlist = Item.find(:all, :select => "name, address", :conditions => { .... } )
Upvotes: 3