Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get all user.name from a database rails

I'm guessing how to retrieve just the names of all the records from a database. The easy way is something like this:

@user=User.all
@list=[]
@user.each do|u|
  @list.push(u.name)
end

but I'm sure if it has to be a oneline query on irb that must fit. Does anyone has an idea?

like image 810
Marc Pursals Avatar asked Aug 10 '13 10:08

Marc Pursals


2 Answers

You should try :

User.all.collect(&:name)

or

User.select("name")

like image 197
Pankhuri Kaushik Avatar answered Oct 04 '22 23:10

Pankhuri Kaushik


There is a built-in method to select one attribute, pluck

User.pluck :name
like image 34
Billy Chan Avatar answered Oct 04 '22 21:10

Billy Chan