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

  • SEARCH
  • Home
  • 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 8439435
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T08:00:28+00:00 2026-06-10T08:00:28+00:00

Evening all, I just had a quick question about SQL average queries. I have

  • 0

Evening all,

I just had a quick question about SQL average queries.

I have a post model which has many ratings. All of the ratings for a particular post are added up and divided by the number of ratings for the average. So this calculation is declared in the post model and saved in the database. In my index view I list out all of the posts, with their author, name and their rating, which comes from the post rating db column.

My question is, why is rails performing all of these SQL average queries when these values have been saved in the database?

my code is as follows:

In the console

Post Load (1.0ms)  SELECT `posts`.* FROM `posts` ORDER BY posts.created_at ASC LIMIT 1
 => #<Post id: 48, user_id: 5, song_name: "Enter Sandman", song: "ewwe wer ere rr erew rewr r erw erw rewedwde", created_at: "2012-08-16 13:35:32", updated_at: "2012-08-22 21:11:34", rating: 5.0, ratings_count: 2> 

Post.rb

def rating
    if self.ratings.any?
      self.rating = self.ratings.average(:rating)
    end
  end

posts/index.html.erb

<legend>Music library</legend>  

    <%= will_paginate @paginate_posts %>

            <% if @paginate_posts.any? %>
                <% @paginate_posts.each do |post| %>
            <h4><%= link_to post.song_name, post %></h4>
                Author: <%= link_to post.user.name, "#" %><br/>
                    <% if post.rating == nil %>
                        No one has rated this yet<br/>
                    <% else %>
                        Rating: <%= post.rating %>/10<br/>
                    <% end %>
                <br/>
        <% end %>
<% end %>

<%= will_paginate @paginate_posts %>

posts_controller.rb index action (I’ve tried eager loading but the avg queries are still there)

def index
    @paginate_posts = Post.paginate(page: params[:page], per_page: 10).includes(:user).search(params[:search])
  end

SQL logs with lots of queries

Started GET "/" for 127.0.0.1 at 2012-08-22 22:51:38 +0100
Processing by PostsController#index as HTML
  Post Load (0.3ms)  SELECT `posts`.* FROM `posts` ORDER BY posts.created_at DESC LIMIT 10 OFFSET 0
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` IN (5)
   (0.3ms)  SELECT COUNT(*) FROM `posts` 
  Rendered posts/_copy.html.erb (0.1ms)
   (0.3ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 63
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 63
   (0.3ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 62
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 62
   (0.2ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 61
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 61
   (0.2ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 60
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 60
   (0.2ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 59
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 59
   (0.2ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 58
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 58
   (0.2ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 57
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 57
   (0.2ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 56
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 56
   (0.2ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 55
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 55
   (0.3ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 54
  CACHE (0.0ms)  SELECT AVG(`ratings`.`rating`) AS avg_id FROM `ratings` WHERE `ratings`.`post_id` = 54
  Rendered posts/index.html.erb within layouts/application (60.8ms)
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1
  Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 2012ms (Views: 1871.7ms | ActiveRecord: 33.1ms)

as usual if you need more code just shout.
many thanks, Andy

  • 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-10T08:00:29+00:00Added an answer on June 10, 2026 at 8:00 am

    You have a method called rating here in post which overrides the accessor on your model, so even if you have a db column ‘rating’ it’s not going to be called when you ask for model.rating, the method will be, which will iterate ratings again. In addition the method is not saving (just setting an attribute does not persist to the db, you need to call save or similar). So if you want to save the value in rating, I’d get rid of that method.

    You should really do this when the post has a rating added or is changed – at that point, call update_rating or something (see below), and then make sure you are calling post.save after (either make it a before_save callback, or call self.update_attribute or self.save explitly in update_rating) – that will save the change to the db, and then you can use

    <%= post.rating %>
    

    in views or anywhere else as a cached average rating value.

    in Post model:

    before_save :update_rating
    
    def update_rating
      if self.ratings.any?
        self.rating = self.ratings.average(:rating)
      end
    end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I posted this question yesterday evening, which has led me to discover a huge
Evening All, Had a question on whether or not the use of Absolute postioning
Evening all, I have the following SQL Query for PDO: DELETE FROM group_members WHERE
Good evening, I would like to have a navigation bar which is centralised to
Evening all. I have the following code that I need looking into - basically
Good Evening All, A client has asked that I develop a web application as
Evening all! I have half a script that I need to change the CSS
I have been trying to connect to mysql all evening using PHP. I know
I have set up a UITableView which has 3 sections in, with 3 rows
Evening all, Actually, it's night. About 11pm. My brain is shutting down and I

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.