Breno Breno - 4 months ago 14
Ruby Question

Fetch ActiveRecord query result as an array of hashes with chosen attributes

The model

User
has
first
,
last
and
login
as attributes. It also has a method called
name
that joins
first
and
last
.

What I want is to iterate through the
Users
records and create an array of hashes with the attributes I want. Like so:

results = []
User.all.map do |user|
record = {}
record["login"] = user.login
record["name"] = user.name
results << record
end


Is there a cleaner way in Ruby to do this?

Answer

I would write:

results = User.all.map { |u| { login: u.login, name: u.name } }
Comments