1

我试图优化我的 Rails 2 应用程序,以限制 mySQL 查询数量。这是一个简单的例子,有 3 个模型:

一篇文章有​​很多图片,通过一个连接模型ArticlePicture。“主图”是第一个,尊重图片的顺序。

class Article < ActiveRecord:Bast
  has_many :articles_pictures, :order => 'sequence'
  has_many :pictures, :through => :articles_pictures, :order => 'sequence'
  has_one :main_picture, :through => :articles_pictures, :source => :picture, :conditions => ["# {ArticlesPicture.table_name}.sequence = ?", 0]
end

文章图片是文章和图片之间的连接模型,具有“序列”字段。

class ArticlesPicture < ActiveRecord::Base
  belongs_to :article
  belongs_to :picture
end

一张图片可以属于许多文章。

class Picture < ActiveRecord::Base
  has_many :articles_pictures
  has_many :articles, :through => :articles_picture
end

在我的控制器中,我调用所有文章,并对其进行分页:

@articles = Article.all.paginate(:per_page => 50)

在我看来,我列出了带有“每个”调用的文章

article.main_picture

显然,Rails 为前 50 张图片调用了“SELECT”,这不是很优化。所以我试着用

@articles = Article.find(:all, :include => :main_picture).paginate(:per_page => 50)

但是Rails会为整个图片表创建一个“SELECT”,即

SELECT `articles_pictures`.*
FROM `articles_pictures`
WHERE (`articles_pictures`.article_id IN (1,2,3,4,5,6,7,8,9,10,11,12,.....)

有什么我忘记的选择吗?

问候

皮埃尔

4

1 回答 1

3

First thing, using all with pagination means no using pagination. Using all makes heavy load on db. It will load all data in memory. For large data it takes long time to load. Sometimes may crash with full memory. So we use pagination to load some data at a time to give user more responsive. So don't use all.

 @articles = Article.all.paginate(:per_page => 50)

Use like this:

 @articles = Article.paginate(:per_page => 50)
 @articles = Article.paginate(:per_page => 50, :include => :main_picture)
于 2013-02-21T16:58:26.527 回答