Home Build list of plucked attributes from belongs_to association
Reply: 0

Build list of plucked attributes from belongs_to association

user785
1#
user785 Published in May 21, 2018, 10:32 pm

Active Record ninjas,

Jumping between languages I've forgotten how to do this: I'm looking for a concise Rails way to get attributes out of an associated model.

class Team < ActiveRecord::Base
  belongs_to :captain, class_name: User

Get array of unique captains who are associated with a team:

Team.all.map(&:captain_id).uniq

What I'd like to do is take that unique list of Captains and grab each one's first_name and last_name.

I want to do

Team.all.map(&:captain_id).uniq.pluck(:first_name, :last_name)

But pluck doesn't work with arrays. I can do this in a couple steps but what's the Rails way?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317214 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO