PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to return a has many object directly

 October 21, 2022     activerecord, has-many, ruby-on-rails     No comments   

Issue

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.



Answered By - Cyril Duchon-Doris
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing