Class User has_many Referrals. Referrals have an instance variable 'point_value.' So on my users/index action I want to list the user info, total referrals, and then total points. However, I am getting the notorious N+1 problem when running this action.
USERS CONTROLLER def index @users = User.find(:all, :include => :referrals) end
INDEX VIEW <% for user in @users %> <tr> <td><%= h user.email %></td> <td>Referrals: <%= user.referrals.size %></td> <td>Points: <%= user.total_points %>
USER.RB MODEL has_many :referrals, :foreign_key => "referer_id"
def total_points self.referrals.sum :point_value end
The index action nails me with a nasty N+2 queries (i have six user records in the test db):
Processing UsersController#index (for 127.0.0.1 at 2009-01-02 15:49:16) [GET] User Load (4.3ms) SELECT * FROM "users" Referral Load (1.4ms) SELECT "referrals".* FROM "referrals" WHERE ("referrals".referer_id IN (1,2,3,4,6,7)) Rendering template within layouts/users Rendering users/index SQL (0.3ms) SELECT sum("referrals".point_value) AS sum_point_value FROM "referrals" WHERE ("referrals".referer_id = 1) SQL (0.3ms) SELECT sum("referrals".point_value) AS sum_point_value FROM "referrals" WHERE ("referrals".referer_id = 2) SQL (0.3ms) SELECT sum("referrals".point_value) AS sum_point_value FROM "referrals" WHERE ("referrals".referer_id = 3) SQL (0.2ms) SELECT sum("referrals".point_value) AS sum_point_value FROM "referrals" WHERE ("referrals".referer_id = 4) SQL (0.3ms) SELECT sum("referrals".point_value) AS sum_point_value FROM "referrals" WHERE ("referrals".referer_id = 6) SQL (0.3ms) SELECT sum("referrals".point_value) AS sum_point_value FROM "referrals" WHERE ("referrals".referer_id = 7)
Is this a failing of the rails .sum method to look inside the collection or am I doing something wrong?