简体   繁体   中英

Rails select from model

in some video i saw next string:

User.select(:email).map(&:email)

tell me plz what does it means

i know that string

User.select(:email)

is selecting only the email column from the db, but i don't understand what means

.map(&:email)

and can we change User.select(:email) to User.pluck(:email)

because from tutorial i understand thats the same methods. is this true?

The map(&:email) maps your array of User s to a map of string containing only the users' emails.

The Array.map iterates over your current array, and creates a new one, by calling the parameter block, and storing the result in the new array. It is equivalent with this:

new_array = []
Users.select(:email).each do |user|
  new_array << user.email
end

User.select(:email)

is returning an array of User objects. The expression

User.select(:email).map(&:email)

selects the email attribute of that objects only. So you end up with an array of email strings. That's at the end the same as

User.pluck(:email)

But it's is different from User.select(:email) for that reason.

See the documentation of pluck als well.

I suppose you already know what map(&:email) gives you, I assume you are asking how and why because it was the same thing that struck me when I first saw this. So this is one of the more advanced ruby magic that voodoo's results back to you :)

Basically lets look at the map function, in itself the most basic usage is to accept a block level command. And after iterating through, takes the default return value and chuck it into an array for you usage. For example, lets see this

list = User.all 

so we get a list of user objects [User model,User model] etc.

list.map do |user|
  user.email
end

if u run this block in IRB or Rails Console, you get ["some@email.here, another@email.here"] etc. so lets catch this result and assign it into a variable

email_list = list.map do |user|
  user.email
end

now email_list should equal to ["some@email.here, another@email.here"] Now that you get the background to the map function, lets delve into the various ways it can accept a parameter

list.map {|user| user.email }

this is the same as the above, but using curly braces to enclose the block logic

list.map(&:email)

this is the shorthand for the above, by defining the block for you, you just supply what child function you wish to run on the block item.

Hope this has given you alittle insight into short hand methods and its block level equivalents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM