HABTM SQL generated


#1

I have a HABTM relationship between 2 tables : companies and services.

I want to find all the companies who provide a particular service so I’m
using @companies = Service.find_by_name(‘servicename’).companies.

But in the development log, rails appears to be making 2 sql calls - one
to find the id of the service and a 2nd to find the companies by that
id.

How can i reduce it to one sql call ?

_Tony


#2

Anthony G. wrote:

I have a HABTM relationship between 2 tables : companies and services.

I want to find all the companies who provide a particular service so I’m
using @companies = Service.find_by_name(‘servicename’).companies.

But in the development log, rails appears to be making 2 sql calls - one
to find the id of the service and a 2nd to find the companies by that
id.

How can i reduce it to one sql call ?

service = Service.find_by_name(‘servicename’, :include => :companies)
@companies = service.companies if service


We develop, watch us RoR, in numbers too big to ignore.