Fill instance variable with all Users from table

77 views Asked by At

I want to fill an instance variable with all my Groups names.

How do I do this?

@groups = Group.name.all

Obviously, this doesn't work. But I don't even know what to search for. The table is called groups, the field name. I am doing this from a different controller but I can see the groups if I use

@groups = Group.first.name

So the associations seem to work.

2

There are 2 answers

0
nesiseka On BEST ANSWER
@groups = Group.all.map(&:name)
0
Max Williams On
@groups = Group.pluck(:name)

http://apidock.com/rails/ActiveRecord/Calculations/pluck

Group.all will load all of the groups table data, and instantiate full models out of them, just to get the names. This is slow and memory intensive. pluck just gets the data you need out of the db in the first place and so is much more efficient.