Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for plucking two attributes from an ActiveRecord object?

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

  1. It loads employees into memory before mapping,
  2. It's verbose (subjective I guess).

Is there a better way?

like image 659
David Tuite Avatar asked Dec 08 '12 11:12

David Tuite


People also ask

What is pluck in Ruby?

Ruby. 2018-05-09 · 2 min read. In Rails, pluck is a shortcut to select one or more attributes without loading the corresponding records just to filter out the selected attributes. It returns an Array of attribute values.

How does pluck work?

The Laravel pluck () as the name suggests, extracts certain values, as suggested. It literally plucks the information out from the given array and produces it as an output. However, it is most effective against objectives, but will work well against arrays too.


2 Answers

UPDATE:

see @jamesharker's solution: from ActiveRecord >= 4, pluck accepts multiple arguments:

@user.employees.pluck(:id, :name) 

PREVIOUS ANSWER:

for a single column in rails >= 3.2, you can do :

@user.employees.pluck(:name) 

... but as you have to pluck two attributes, you can do :

@user.employees.select([:id, :name]).map {|e| {id: e.id, name: e.name} }  # or map &:attributes, maybe 

if you really need lower-level operation, just look at the source of #pluck, that uses select_all

like image 168
m_x Avatar answered Sep 23 '22 07:09

m_x


In ActiveRecord >= 4 pluck accepts multiple arguments so this example would become:

@user.employees.pluck(:id, :name) 
like image 27
jamesharker Avatar answered Sep 21 '22 07:09

jamesharker