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
Is there a better way?
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.
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.
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
In ActiveRecord >= 4 pluck accepts multiple arguments so this example would become:
@user.employees.pluck(:id, :name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With