Ruby rails - select only few columns from the data base

前端 未结 6 1506
[愿得一人]
[愿得一人] 2020-12-15 02:16

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

相关标签:
6条回答
  • 2020-12-15 02:52
    @itemlist = Item.select('name, address').where(...#some condition)
    
    0 讨论(0)
  • 2020-12-15 02:59

    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 => { .... } )
    
    0 讨论(0)
  • 2020-12-15 03:04

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

    0 讨论(0)
  • 2020-12-15 03:09

    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.

    0 讨论(0)
  • 2020-12-15 03:13

    Rails 3:

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

    0 讨论(0)
  • 2020-12-15 03:16

    Try this:

    @itemlist = Item.find(:all, :select => "name, address", :conditions => { .... } )
    
    0 讨论(0)
提交回复
热议问题