I have code that generates a problem with querying database N + 1.
The problem occurs if the page is not unpacked. When the page is cached, adding .includes actually results in an unnecessary database call. I am wondering how to get around this problem.
my applicaiton_helper.rb contains the following:
module ApplicationHelper def by(article) "By #{article.username} on #{article.created_at.strftime('%B %e, %Y')}" end end
my article.rb contains:
class Article < ActiveRecord::Base belongs_to :user def username user.username end end
and my article_controller.rb contains:
class ArticlesController < ApplicationController def index @articles = user_signed_in? ? Article.all : Article.all.published.limit(13) end end
This method is a username method that invokes a user model call. As stated above, when the page has not yet been cached, this leads to a helper method by(article) to continuously invoke the user model without any high load. However, since I cache my views, this inefficiency only occurs once. If I change my article_controller.rb to the following:
class ArticlesController < ApplicationController def index @articles = user_signed_in? ? Article.all.includes(:user) : Article.all.published.limit(13).includes(:user) end end
N + 1 problem disappears when loading the first page, but after reloading the page I get the unnecessary .includes .
Any idea how I can fix this small glitch?
Thanks!
source share