Haseeb Ahmad Haseeb Ahmad - 3 months ago 14
Ruby Question

How to get columns of belongs_to table?

college.rb

has_many :tenant_colleges


tenant_college.rb

belongs_to :college


I want to get attribute name of college along with all tenant_college attributes

I do

TenantCollege.select("tenant_colleges.*, colleges.name").joins(:college)


But it doesn't give college name

Answer

Try eager loading associations, like this

   tenant_colleges = TenantCollege.includes(:colleges)
    tenant_colleges.each do |tc|
      puts tc.college.name
    end 

EDIT
Like @lcguida suggested its better to go with two separate queries. If you want to get that in a single query use the .select method as we normally do

TenantCollege.joins(:colleges).select("tenant_colleges.*, colleges.name")

OR

TenantCollege.joins("LEFT JOIN colleges ON tenant_colleges.id = colleges.tenant_id")
  .select('tenant_colleges.*', 'colleges.name')