Ruby rails - select only few columns from the data base

Ruby on-RailsRubyRuby on-Rails-3Rails Activerecord

Ruby on-Rails Problem Overview


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;

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Rails 3:

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

Solution 2 - Ruby on-Rails

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


Solution 3 - Ruby on-Rails

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

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

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.

Solution 6 - Ruby on-Rails

Try this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMajorisView Question on Stackoverflow
Solution 1 - Ruby on-RailsnyaaView Answer on Stackoverflow
Solution 2 - Ruby on-Railsdku.rajkumarView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMichelle TilleyView Answer on Stackoverflow
Solution 4 - Ruby on-RailsKuberanView Answer on Stackoverflow
Solution 5 - Ruby on-Railseriel marimonView Answer on Stackoverflow
Solution 6 - Ruby on-Railscoder_timView Answer on Stackoverflow