ruby-on-rails-3ruby-on-rails-3.1declarative-authorizationrails-bullet

Fix N+1 query in "declarative_authorization" gem using gem "bullet"


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?


Solution

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