dimanche 17 mai 2020

Association in rails Model

Below is the model Structure.

class JobFamilyRole < ActiveRecord::Base
   belongs_to :JobFamily
   belongs_to :JobRole
   belongs_to :Organization
end

class JobFamily < ActiveRecord::Base
   has_many :JobFamilyRoles
   has_many :JobRoles
end

I am looking for below result from the above JobFamilyRole table.

  {
     job_family1: [job_role1, job_role2],
     job_family2: [job_role1, job_role2, job_role3]
     ...
  }

I achieved this Result from below query:

  job_family_roles = JobFamilyRole.where(:organization_id => org_id)
  results = {}
  job_family_roles.each do |job_family_role|
    job_family = JobFamily.find(job_family_role.job_family_id)
    result[job_family.name] = job_family.job_roles.collect(&:title)
  end

 puts results 

But Above query doesn't look optimized one so can anyone help me to write the optimized query. In our App org_id is present.

Aucun commentaire:

Enregistrer un commentaire