Haseeb Ahmad Haseeb Ahmad - 1 year ago 77
Ruby Question

How to get columns of belongs_to table?


has_many :tenant_colleges


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 Source

Try eager loading associations, like this

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

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")


TenantCollege.joins("LEFT JOIN colleges ON tenant_colleges.id = colleges.tenant_id")
  .select('tenant_colleges.*', 'colleges.name')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download