I am new to rails and would appreciate help in optimizing the use of my database.
Is there a way to load two models connected to each other using a single DB query?
I have two models Person and Image:
class Person < ActiveRecord::Base
has_many :images
end
class Image < ActiveRecord::Base
belongs_to :person
end
I would like to upload a set of people and their associated images with one trip to the database using the connect command. For example, in SQL, I can load all the data I need with the following query:
select * from people join images on people.id = images.person_id where people.id in (2, 3) order by timestamp;
So I was hoping this rail snippet would do what I needed:
>> people_and_images = Person.find(:all, :conditions => ["people.id in (?)", "2, 3"], :joins => :images, :order => :timestamp)
This code executes the SQL statement that I expect and loads the Person instances I need. However, I see that accessing Person images leads to an additional SQL query.
>> people_and_images[0].images
Image Load (0.004889) SELECT * FROM `images` WHERE (`images`.person_id = 2)
: include find() , SELECT, JOIN.
Rails, SQL, , , .
. !