如何仅从模型中选择特定属性? [英] How to select only specific attributes from a model?

查看:47
本文介绍了如何仅从模型中选择特定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想从模型(id,name)中选择特定属性.

I want to select only specific attributes from a model(id,name).

SQL 命令可以是例如:

The SQL-command can be for example:

SELECT id,name,username FROM Users

SELECT id,name,username FROM Users

你知道我该如何处理吗?

Do you know how I can handle this?

推荐答案

查找方法有一个 :select 选项.这允许您执行以下操作:

There's a :select option on find methods. This allows you to do:

User.find(:all, :select => 'id, name, username')

返回的对象将是具有可用属性的 User 实例.

The returned objects will be User instances with those attributes available.

或者,如果您真的只想要值而不将它们包装为 User 实例.您可以向 User 添加方法以返回它们.

Or if you really want just the values without wrapping them us as User instances. You can add a method to User to return them.

def self.get_ids_and_names
  self.connection.select_all("select id, name, username from users")
end

它将返回一个哈希数组,将列名映射到该行的值.例如.[{'id' =>1, '姓名' =>'user1', '用户名' =>'username1'}, ... ]

which will return an array of hashes mapping column name to the value for that row. E.g. [{'id' => 1, 'name' => 'user1', 'username' => 'username1'}, ... ]

这篇关于如何仅从模型中选择特定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆