Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8453445
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T11:46:35+00:00 2026-06-10T11:46:35+00:00

I’m trying to optimise some N+1 queries in active record for the first time.

  • 0

I’m trying to optimise some N+1 queries in active record for the first time. There are 3 to kill – 2 went very easily with a .includes call, but I can’t for the life of me figure out why the third is still calling a bunch of queries. Relevant code below – if anyone has any suggestions, I’d be really appreciative.

CONTROLLER:

@enquiries = Comment.includes(:children).faqs_for_project(@project)

MODEL;

def self.faqs_for_project(project)
  Comment.for_project_and_enquiries(project, project.enquiries).where(:published => true).order("created_at DESC")
end

(and the relevant scope)

scope :for_project_and_enquiries, lambda{|p, qs| where('(commentable_type = ? and commentable_id = ?) or (commentable_type = ? and commentable_id IN (?))', "Project", p.id, "Enquiry", qs.collect{|q| q.id})}

VIEW:

...
= render :partial => 'comments/comment', :collection => @enquries
...

(and that offending line in the partial)

...
= 'Read by ' + pluralize(comment.acknowledgers.count, 'lead')
...

Two SQL queries are called for each comment. The 2 queries are:

SQL (2.8ms)  SELECT COUNT(*) FROM "users" INNER JOIN "acknowledgements" ON "users".id = "acknowledgements".user_id WHERE (("acknowledgements".feedback_type = 'Comment') AND ("acknowledgements".feedback_id = 177621))
CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1295 LIMIT 1

I would have thought appending (:user, :acknowledgements) into the controller’s .includes would have solved the problem, but it doesn’t seem to have any effect. If anyone has any suggestions on what I’m missing, I’d be really appreciative

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T11:46:36+00:00Added an answer on June 10, 2026 at 11:46 am

    I believe in your Comment table you want to add a :acknowledgers_count column as a counter cache

    has_many :acknowledgers, ....., counter_cache: true
    

    You will need to create a migration to add the :acknowledgers_count column to the comments table. Rails should take care of the rest.

    You can learn more about the ActiveRecord::CounterCache api here.

    The count method in comment.acknowledgers.count is overloaded in ActiveRecord to first check if a counter cache column exists, and if it does, it returns that directly from the model (in this case the Comment model) without having to touch the database again.

    Finally, there was very recently a great Railscast about a gem call Bullet that can help you identify these query issues and guide you toward a solution. It covers both counter caches and N+1 queries.

    As @ismaelga pointed out in a comment to this answer, it’s a generally better practice to call .size instead of .count on a relation. Check out the source for size:

    def size
      loaded? ? @records.length : count
    end
    

    If the relation is already loaded it will just call length on it, otherwise it will call count. It’s an extra check to try and prevent the database from unnecessarily being queried.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I'm trying to select an H1 element which is the second-child in its group

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.