如何在 Rails Active Record 中从用户 table 创建数据数组?

How do I create array of data from Users table in Rails Active Record?

我有一个用户 table,其列为 full_name, email, phone, address, city, state, zip

我需要从用户 table 创建一个数组,其中包含此格式的全名和电子邮件 ["user1.full_name, user1.email", "user2.full_name, user2.email" 等]

我在编写此查询时遇到问题。

这是我目前所拥有的

#create empty arrays
full_names = []
emails = []
#populate the full_names array
user_full_name = User.all
user_full_name.each{|x| full_names<<x.full_name}
#populate the emails array
user_email = User.all
user_email.each{|x| emails<<x.email}

#combine the two arrays
full_names.zip(emails)

但这给了我一个多维数组 [[[full_name, 电子邮件"], ["full_name, 电子邮件"] 等]

如何获取格式为 ["full_name, 电子邮件", "full_name, 电子邮件" 等]

User.all.map do |user|
  "#{user.full_name}, #{user.email}"
end

Array#map


提供更多信息。当您使用 ActiveRecord::QueryMethod (e.g. you make a query through ActiveRecord) the result is not actually an array, however it behaves like an array, and by calling an array method on it, you fetch the results (See ActiveRecord::Relation) 时。那是一口,但希望下面的例子会更清楚:

# This builds a query but doesn't actually fire it!
users = User.all

# chain onto the query - it still won't be fired yet
users = users.where.not(name: "Rick")

# see the query that will be run
users.to_sql

# check the type of this variable
users.class
# => ActiveRecord::Relation

# evaluates the query
users.count

# evaluates the query
users.to_a

# evaluates the query
users.any? { |user| user.email.nil? }

# evaluates the query
users.map { |user| user.full_name }

# evaluates the query
# does the same thing as the previous line
users.pluck(:first_name)

这里有两个*可能的解法及其对应的SQL:

# SELECT "users"."full_name", "users"."email" FROM "users"
User.pluck('full_name', 'email').map{ |u| u.join(', ')}.flatten

# SELECT "users".* FROM "users"
User.all.map { |u| "#{u.full_name}, #{u.email}" }

所以pluckall.map更有效率,因为它只选择你想要的属性。

* 这两个在之前的回答中都有提到。