Prev | Current Page 96 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

For example, assume that, in your social
network, you have the following classes:
class Person < ActiveRecord::Base
has_many :favorites
end
class Favorite < ActiveRecord::Base
belongs_to :person
belongs_to :band
end
class Band < ActiveRecord::Base
belongs_to :location
end
class Location < ActiveRecord::Base
end
If you wish to find people who like bands that are based in a particular city, you can use
the :include hash as follows:
city = 'Boston'
Person.find :all, :include => { :favorites => { :bands => { :location => {} } } },
:conditions => ["locations.city = ?", city]
The generated SQL would be
SELECT *
FROM people
LEFT OUTER JOIN favorites
ON people.id=favorites.person_id
LEFT OUTER JOIN bands
ON favorites.band_id=bands.id
LEFT OUTER JOIN locations
ON bands.location_id=locations.id
WHERE locations.city = `Boston`
The SQL will look like the preceding statement under most circumstances. However, if the
tables included loop back on themselves, the table names will need to be relabeled. Therefore,
if we had the following class
CHAPTER 2 ?–  ACTIVE RECORD AND SQL 29
class Person < ActiveRecord::Base
belongs_to :parent, :class_name => "Person"
has_many :children, :class_name => "Person", :foreign_key => :parent_id
end
we would need to use the following statement to find people who have a child with a particular
name:
Person.


Pages:
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108