我有一些代码正在生成 N+1 数据库查询问题。
仅当页面未缓存时才会出现此问题。缓存页面后,添加 .includes
实际上会导致不必要的数据库调用。我想知道如何解决这个问题。
我的 applicaiton_helper.rb 包含以下内容:
module ApplicationHelper
def by(article)
"By #{article.username} on #{article.created_at.strftime('%B %e, %Y')}"
end
end
我的 文章.rb 包含:
class Article < ActiveRecord::Base
belongs_to :user
def username
user.username
end
end
和我的文章 Controller .rb 包含:
class ArticlesController < ApplicationController
def index
@articles = user_signed_in? ? Article.all : Article.all.published.limit(13)
end
end
有问题的方法是
username
方法,它调用 User 模型。如前所述,当页面尚未被缓存时,这将导致 by(article)
helper 方法可以在没有任何预加载的情况下连续调用 User 模型。但是,由于我正在缓存我的 View ,因此这种低效率只会发生一次。如果我将articles_controller.rb 更改为以下内容:class ArticlesController < ApplicationController
def index
@articles = user_signed_in? ? Article.all.includes(:user) : Article.all.published.limit(13).includes(:user)
end
end
N+1 问题在第一页加载时消失,但随后我得到一个不必要的
.includes
重新加载页面时。知道如何解决这个小故障吗?
谢谢!
最佳答案
不知何故,这解决了我的问题:
class Article < ActiveRecord::Base
belongs_to :user
delegate :username, to: :user
end
所以我只是将一篇文章的用户名调用委托(delegate)给 User 模型。漂亮、干净、实用:子弹不再提示。
关于ruby-on-rails - rails 4 : small N+1 issue for uncached page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34632376/