0

I have a User table with the columns full_name, email, phone, address, city, state, zip

I need to create an array from the User table that contains the fullname and email in this format ["user1.full_name, user1.email", "user2.full_name, user2.email" etc]

I am having trouble writing this query.

This is what I have so far

#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)

But that gives me a multidimensional array of [["full_name, email"], ["full_name, email"] etc]

How do I get it in the format of ["full_name, email", "full_name, email" etc]

2 Answers 2

1

Here are two* possible solutions and their corresponding 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}" }

So pluck is more efficient than all.map because it only selects the attributes you want.

* Both of which were mentioned in an earlier answer.

Sign up to request clarification or add additional context in comments.

Comments

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

See Array#map


To give a little more info on this. When you use an 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). That was a mouthful, but hopefully the following examples will be clearer:

# 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.