Rails - 给定一组用户 - 如何仅获得电子邮件的输出? [英] Rails - given an array of Users - how to get a output of just emails?

查看:28
本文介绍了Rails - 给定一组用户 - 如何仅获得电子邮件的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

@users = User.all

用户有多个字段,包括电子邮件.

User has several fields including email.

我希望能够做的是获得所有@users 电子邮件的列表.

What I would like to be able to do is get a list of all the @users emails.

我试过了:

@users.email.all but that errors w undefined

想法?谢谢

推荐答案

(根据大众需求,作为真实答案发布)

(by popular demand, posting as a real answer)

我不喜欢什么 fl00r 的解决方案 是它在数据库中为每个记录实例化一个新的 User 对象;这只是不缩放.对于只有 10 封电子邮件的表格来说,这很棒,但是一旦您开始处理数千封电子邮件,您就会遇到问题,主要是 Ruby 的内存消耗.

What I don't like about fl00r's solution is that it instantiates a new User object per record in the DB; which just doesn't scale. It's great for a table with just 10 emails in it, but once you start getting into the thousands you're going to run into problems, mostly with the memory consumption of Ruby.

可以通过在模型上使用 connection.select_values 和一点点 ARel 优点来解决这个小问题:

One can get around this little problem by using connection.select_values on a model, and a little bit of ARel goodness:

User.connection.select_values(User.select("email").to_sql)

这将为您提供数据库中电子邮件地址的直字符串.不关心用户对象,并且比直接的 User.select("email") 查询更好,但我不会说这是最佳比例".可能有更好的方法来做到这一点,但我还不知道.

This will give you the straight strings of the email addresses from the database. No faffing about with user objects and will scale better than a straight User.select("email") query, but I wouldn't say it's the "best scale". There's probably better ways to do this that I am not aware of yet.

重点是:String 对象将使用 wayUser 对象更少的内存,因此您可以拥有更多的内存.这也是一个更快的查询,并且不会走很长的路(运行查询,然后映射值).哦,map 也需要更长的时间.

The point is: a String object will use way less memory than a User object and so you can have more of them. It's also a quicker query and doesn't go the long way about it (running the query, then mapping the values). Oh, and map would also take longer too.

那你就得手动构造SQL了,很抱歉.

Then you'll have to construct the SQL manually, I'm sorry to say.

User.connection.select_values("SELECT email FROM users")

只是提供了 Rails 3 提供的帮助程序的另一个示例.

Just provides another example of the helpers that Rails 3 provides.

这篇关于Rails - 给定一组用户 - 如何仅获得电子邮件的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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