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

Build list of plucked attributes from belongs_to association

Meltemi
1#
Meltemi Published in 2017-11-09 21:01:21Z

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?

MrYoshiji
2#
MrYoshiji Reply to 2017-11-09 22:05:20Z

You can do the following:

captain_ids = Team.all.select(:captain_id)
User.where(id: captain_ids).pluck(:first_name, :last_name)

Rails should be smart enough to do a nested select.

The other option is the joins, it can be more efficient (faster), but in my test cases a sub-select was 3 times faster than an INNER JOIN. Try it out yourself :)

potashin
3#
potashin Reply to 2017-11-09 22:15:28Z

You can use joins and group:

Team.joins(:captain)
    .group("users.id")
    .pluck("users.first_name", "users.last_name")
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO