4

Currently I am working on one big web application and to make it work faster I decided to refactor all N+1 queries (to decrease number of requests to database, http://rails-bestpractices.com/posts/29-fix-n-1-queries). So I installed gem "bullet" which doesn`t work with Rails 3.1.1 now (you can use fork from https://github.com/flyerhzm/bullet). When using declarative_authorization gem on each page I get same alerts:

N+1 Query detected
  Role => [:permissions]
  Add to your finder: :include => [:permissions]

N+1 Query detected
  Permission => [:permission_rules]
  Add to your finder: :include => [:permission_rules]

CACHE (0.0ms)  SELECT "roles".* FROM "roles" 
  CACHE (0.0ms)  SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 1
  CACHE (0.0ms)  SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 2
  CACHE (0.0ms)  SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 3
  CACHE (0.0ms)  SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 4
  CACHE (0.0ms)  SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 6
  CACHE (0.0ms)  SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 7
  CACHE (0.0ms)  SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 8
  CACHE (0.0ms)  SELECT "permission_rules".* FROM "permission_rules" INNER JOIN "permission_rules_permissions" ON "permission_rules"."id" = "permission_rules_permissions"."permission_rule_id" WHERE "permission_rules_permissions"."permission_id" = 30
  CACHE (0.0ms)  SELECT "permission_rules".* FROM "permission_rules" INNER JOIN "permission_rules_permissions" ON "permission_rules"."id" = "permission_rules_permissions"."permission_rule_id" WHERE "permission_rules_permissions"."permission_id" = 31

...

Could you please help me with that and to make this queries faster?

usha
  • 28,973
  • 5
  • 72
  • 93
makaroni4
  • 2,281
  • 1
  • 18
  • 26

1 Answers1

2

I would remove the gem but add the :includes in each of the two models.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 2
    Michael is absolutely right and I just didn`t noticed couple of files in "config" directory, where rules were loaded so yep, I just add includes(:permission_rules) to user_role.permissions and it works great right now! I recommend you to pass through codeschool.com Rails Best Practices, in lesson 4 there is a cool explanation of N+1 queries. – makaroni4 Nov 28 '11 at 10:00
  • 1
    +1 mararoni4 - I (have done and) think Code School is awesome! – Michael Durrant Nov 28 '11 at 11:18