shahidkamal
shahidkamal

Reputation: 119

Getting details of other columns from active record joins

I have following join where I am getting Review tables all columns but I need to add other columns but it is showing nothing for other column.

Review.joins(division: [{company: :region}, :departments, :employees]).select('reviews.id, companies.name as company, region.name, divisions.name as division).limit(10)

But I am getting only Reivews

[#<Review:0x00007ff5006bb910 id: 1>,
...

How can I get division.id, company.name and region.name

Upvotes: 0

Views: 98

Answers (1)

Joel Blum
Joel Blum

Reputation: 7878

What you are seeing (only Review objects) is what you're supposed to see, Rails performs the join between Review, Devision, Company etc etc and brings you back the Review records resulting from that join. However the selected aliased columns should be available as methods on the Review records:

reviews = Review.joins(...)
reviews.first.company
reviews.first.division

Note that inspect method doesn't show non column attributes so your console might hide the aliased columns (company, division) but they are there.

Since it seems like you're not after only filtering but you need association data, you might be better off exchanging this with eager_loading since if you try to access the associations like that you will fire n+1 queries.

Review.includes(division: [{company: :region}, :departments, :employees]).select('reviews.id, companies.name as company, region.name, divisions.name as division).limit(10)

Upvotes: 1

Related Questions