Forum: Ruby on Rails Left Joins with Rails?

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.
0df56f2edb0d80e81c5c0ef1ca91690e?d=identicon&s=25 Joel Oliveira (Guest)
on 2006-03-02 19:51
(Received via mailing list)
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
Bc80625db60e9db4394c51d6c1892b49?d=identicon&s=25 Derrick Spell (Guest)
on 2006-03-02 20:03
(Received via mailing list)
> 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 Spell
This topic is locked and can not be replied to.