Ruby-on-rails 如何从用户数组中提取电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21901142/
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-02 23:23:03  来源:igfitidea点击:

how to pluck email from array of users

ruby-on-railsruby

提问by Rahul Singh

If I do User.all.pluck(:email)then it works fine.

如果我这样做,User.all.pluck(:email)那么它工作正常。

But if I do

但如果我这样做

arr = Array.new
arr = User.all

and then

进而

arr.pluck(:email)

this is raising following error

这是引发以下错误

undefined method `pluck' for #<Array:0x007f4ff8daf3c8>

which means I cannot use pluck with arrays, so how can we get particular field value from an array of records in just one line like above. I don't want to loop through each record in an array.

这意味着我不能将 pluck 与数组一起使用,那么我们如何才能像上面那样在一行中从一组记录中获取特定的字段值。 我不想遍历 array 中的每个记录

回答by apneadiving

pluckis useful to do a minimalist db query.

pluck对做一个极简的数据库查询很有用。

When you have an array, just use map:

当你有一个数组时,只需使用map

arr.map(&:email)

回答by steakchaser

Use collect, it's an Array method:

使用collect,它是一个数组方法:

arr.collect{|u| u.email}

回答by xlembouras

pluck(:x)is the equivalent of select(:x).map(&:x)on an ActiveRecordcollection.

pluck(:x)相当于select(:x).map(&:x)ActiveRecord集合上。

If you have an array, Array#mapand its alias Array#collectdo the same job.

如果你有一个数组,Array#map它的别名Array#collect做同样的工作。

If you use

如果你使用

User.scoped.pluck(:email)

User.scoped.pluck(:email)

your query will be like

您的查询将类似于

SELECT users.email FROM users

SELECT users.email FROM users

So, to answer the question, you can NOT use pluck on an array, pluckis an ActiveRecord::Calculationsmethod, not an array one.

因此,要回答这个问题,您不能在数组上使用 pluck,pluck是一种ActiveRecord::Calculations方法,而不是数组。

回答by Akash Agrawal

Converting to array this way is a memory hogger. Instead you can use:

以这种方式转换为数组是一种内存占用。相反,您可以使用:

arr = User.scoped
arr.pluck :email

or in a more easy to read:

或者更容易阅读:

User.scoped.pluck :email

This will make sure that actual user objects are not loaded into memory until they are required.

这将确保实际的用户对象在需要之前不会加载到内存中。