Ruby rails - 从数据库中只选择几列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10256390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:16:31  来源:igfitidea点击:

Ruby rails - select only few columns from the data base

ruby-on-railsrubyruby-on-rails-3rails-activerecord

提问by Kapish M

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.

rails 构造 sql 查询以仅从数据库中选择某些列的方式是什么,我有一些大数据字段,我想避免从连续的定期 ajax 调用中加载。不必要的阅读是资源消耗和缓慢的。

@itemlist = Item.find(:all, :conditions => { .... } ) #this select all columns 

I am looking for SELECT name, address FROM users;instead of SELECT * FROM users;

我正在寻找SELECT name, address FROM users;而不是SELECT * FROM users;

回答by nyaa

Rails 3:

轨道 3:

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

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

回答by dku.rajkumar

Make use of :selectconstruct. Try this:

利用:select构造。尝试这个:

@itemlist = Item.select('name, address', conditions: { .... } )

For previous version of Rails:

对于以前版本的 Rails:

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

回答by Michelle Tilley

Using Arel (aka in Rails 3), use:

使用 Arel(在 Rails 3 中又名),使用:

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

Also, it seems .select gets ignored if you tack on a scope that has an :include => ...

此外,如果您添加具有 :include => ... 的范围,似乎 .select 会被忽略。

回答by Kuberan

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

回答by coder_tim

Try this:

尝试这个:

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

回答by eriel marimon

If want to select specific columns from the rails console, pluck(will work. Example:

如果要从 中选择特定列rails consolepluck(将起作用。例子:

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.

请注意,这也适用于 Rails 应用程序。