Ruby-on-rails 如何仅从模型中选择特定属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1237557/
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
How to select only specific attributes from a model?
提问by Shadwell
I want to select only specific attributes from a model(id,name).
我只想从模型(id,name)中选择特定的属性。
The SQL-command can be for example:
例如,SQL 命令可以是:
SELECT id,name,username FROM Users
SELECT id,name,username FROM Users
Do you know how I can handle this?
你知道我该如何处理吗?
回答by Ross
Pretty old question, but the rails 3 way would be:
很老的问题,但 Rails 3 的方式是:
User.pluck(:id)
回答by Shadwell
There's a :selectoption on find methods. This allows you to do:
:selectfind 方法有一个选项。这允许您执行以下操作:
User.find(:all, :select => 'id, name, username')
The returned objects will be Userinstances with those attributes available.
返回的对象将是User具有可用属性的实例。
Or if you really want just the values without wrapping them us as Userinstances. You can add a method to Userto return them.
或者,如果您真的只想要这些值而不将它们包装为我们的User实例。您可以添加一个方法User来返回它们。
def self.get_ids_and_names
self.connection.select_all("select id, name, username from users")
end
which will return an array of hashes mapping column name to the value for that row. E.g. [{'id' => 1, 'name' => 'user1', 'username' => 'username1'}, ... ]
这将返回一个哈希数组,将列名映射到该行的值。例如[{'id' => 1, 'name' => 'user1', 'username' => 'username1'}, ... ]
回答by ez.
You can also do
你也可以这样做
User.find(:all).map(&:id)
to get a list of the user ids if you are trying to get a list of user's ids or names
如果您尝试获取用户 ID 或名称列表,则获取用户 ID 列表
回答by Xavier
You can also pass in an array, like so:
您还可以传入一个数组,如下所示:
Model.all.select ['id', 'title']
回答by Khanh Pham
We can use selectfor symbolor stringsuch as:
我们可以select用于symbol或string例如:
User.select("id, name, username")
or
或者
User.select(:id, :name, :username)
回答by Ezequiel García
actually for you only need write this
其实你只需要写这个
@user= User.select(:attributeN, :attributeN......., attributeN)
respond_to do |format|
format.json {
render json: @user
}
回答by Daniel Szmulewicz
In mongoid, that would be:
在 mongoid 中,这将是:
User.only(:name, :username).where(id: params[:id]).first
回答by imechemi
SQL
SQL
SELECT id,name,username FROM Users
SELECT id,name,username FROM Users
RUBY
红宝石
User.select(:id, :name, :username)
User.select(:id, :name, :username)
with condition, you can write like:
User.select(:id, :name, :username).find_by(:age 22)
有条件,你可以这样写:
User.select(:id, :name, :username).find_by(:age 22)

