rubyonrails:Ruby on rails开发从头来( 5十 9)- ActiveRecord基础(预加载子记录)

  预加载子记录讨论问题和“延迟加载”是相同通常Active Record会推迟从数据库中加载子记录直到你需要他们例如通过Rdoc中例子我们假定博客个Model像下面这样:

Post < ActiveRecord::Base
belongs_to :author
has_many :comments, :order => 'created_on DESC'
end


  如果我们遍历所有post访问作者和评论属性我们使用个Sql查询来返回posts表中多条记录并且对于每条post记录都要执行次Sql来访问authors表和comments表总共是2n+1次

for post in Post.find(:all)
puts "Post: #{post.title}"
puts "Written by: #{post.author.name}"
puts "Last comment _disibledevent=> [:author, :comment])
# ...
end


Tags:  rubyonrails安装 rubyforrails rubyrails rubyonrails

延伸阅读

最新评论

发表评论