【发布时间】:2009-08-23 20:34:58
【问题描述】:
我是 Rails 新手,希望能帮助我优化我的数据库使用。
有没有办法通过一个数据库查询加载两个相互关联的模型?
我有两个模型 Person 和 Image:
class Person < ActiveRecord::Base
has_many :images
end
class Image < ActiveRecord::Base
belongs_to :person
end
我想使用 join 命令在一次访问数据库的过程中加载一组人员及其相关图像。例如,在 SQL 中,我可以使用以下查询加载我需要的所有数据:
select * from people join images on people.id = images.person_id where people.id in (2, 3) order by timestamp;
所以我希望这个 rails sn-p 能满足我的需要:
>> people_and_images = Person.find(:all, :conditions => ["people.id in (?)", "2, 3"], :joins => :images, :order => :timestamp)
此代码执行我期望的 SQL 语句并加载我需要的 Person 实例。但是,我发现访问人的图像会导致额外的 SQL 查询。
>> people_and_images[0].images
Image Load (0.004889) SELECT * FROM `images` WHERE (`images`.person_id = 2)
在调用 find() 时使用 :include 选项确实会加载两个模型,但是通过与 JOIN 一起执行它会花费我额外的 SELECT。
我想在 Rails 中做我可以在 SQL 中做的事情,即通过一个查询获取我需要的所有数据。
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
您找到解决方案了吗?非常感谢任何帮助
标签: ruby-on-rails join