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
@itemlist = Item.select('name, address').where(...#some condition)
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 => { .... } )
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 => ...
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.
Rails 3:
Item.select("name, address").where( .... )
Try this:
@itemlist = Item.find(:all, :select => "name, address", :conditions => { .... } )