Forum: Ruby on Rails HABTM SQL generated

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Anthony G. (Guest)
on 2006-02-26 17:50
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
Mark Reginald J. (Guest)
on 2006-02-26 17:56
(Received via mailing list)
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.
This topic is locked and can not be replied to.