Left Joins with Rails?


#1

Everyone,

I have two tables (assuming their most logical types):

apartments
id
address
bedrooms
bathrooms
googlemaps_id

googlemaps
id
url

the models:

class Apartment < ActiveRecord::Base
	has_one :googlemap
end

class Googlemap < ActiveRecord::Base
	belongs_to :listing
end

I would like to find_all by searching the attributes in apartment, and
also return the google map associated with that apartment, and a null
(or empty string) if there’s no google map in its table associated
with the apartment’s id. In sql I would do this with a left join, and
while I could used the find_by_sql method I was wondering if there’s a
more practical “Rails” way of doing this.

In the apartments controller I have something for found results like

def results
@apartments = Listing.find(:all, :conditions => [“bedrooms=? AND
bathrooms=?”, :params])
end

But that will only return the columns in Apartments. How would I do
that to get the googlemaps url if there is a corresponding value?

Thanks all!

  • Joel

#2

I would like to find_all by searching the attributes in apartment, and
bathrooms=?", :params])
end

But that will only return the columns in Apartments. How would I do
that to get the googlemaps url if there is a corresponding value?

First of all, your model name is Apartment, not Listing, so the code
you have above should only return an error. But that aside…

When you specified the has_one and belongs_to in your models, you
told Rails how to set up the left join. This means you don’t need to
do it yourself. Any Apartment object will have a class method called
googlemap. This is how you get the corresponding googlemap.

@apartment = Apartment.find(:first)
@apartment.googlemap

Now, if you know for sure that you are going to use the googlemap,
and you don’t want rails to use two sql statements (which it would
using the above code), then you can use the :include symbol to
specify what we call “eager loading”. Eager loading just means “go
ahead and do the join cuz I know I’m gonna need it”.

@apartment = Apartment.find(:first, :include => :googlemap)
@apartment.googlemap

-Derrick S.