Is there a shorter way to do the following (
@user.employees.map { |e| { id: e.id, name: e.name } }
# => [{ id: 1, name: 'Pete' }, { id: 2, name: 'Fred' }]
User has_many employees. Both classes inherit from ActiveRecord::Base.
Two things I don’t like about the above
- It loads employees into memory before mapping,
- It’s verbose (subjective I guess).
Is there a better way?
UPDATE:
see @jamesharker’s solution: from ActiveRecord >= 4,
pluckaccepts multiple arguments:PREVIOUS ANSWER:
for a single column in rails >= 3.2, you can do :
… but as you have to pluck two attributes, you can do :
if you really need lower-level operation, just look at the source of #pluck, that uses
select_all