Search code examples
ruby-on-railsactiverecordhas-many

How to return a has many object directly


I’m trying to find a way to return a has many object directly instead of the parent object with the relation intact

Here is my ProjectExternalTeam model, for which I am looking to return the guests directly (a collection of users)

class ProjectExternalTeam < ActiveRecord::Base
  belongs_to :project
  belongs_to :guest, class_name: 'User', foreign_key: 'member_id'
  belongs_to :owner, class_name: 'User', foreign_key:'invited_by_id'
end

Right now I am using something like

gus = []
gg = ProjectExternalTeam.where(account_id:1)
gg.each do |g| gus.push(g.guest) end

With this gus ends up being a collection of users. I feel that there must be some easier way to do this, something like

gus = ProjectExternalTeam.where(account_id:1).guests

Thanks in advance


Solution

  • You want to map. Using the &:method syntax (a shortcut for xxx.map do {|sth| sth.method}) this gives

    gus = ProjectExternalTeam.where(account_id: 1).map(&:guest)
    

    However, see @Gen answer for an optimised DB query.