Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

has_role? does not use preloaded data, but always makes a query #547

Open
vfonic opened this issue Jun 10, 2020 · 0 comments
Open

has_role? does not use preloaded data, but always makes a query #547

vfonic opened this issue Jun 10, 2020 · 0 comments

Comments

@vfonic
Copy link

vfonic commented Jun 10, 2020

I preload current user roles in my app like this (I use devise for auth):

class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= super.tap do |user|
      ::ActiveRecord::Associations::Preloader.new.preload(user, :roles)
    end
  end
end

When I call user.has_role?(:staff, company), the SQL query is executed, disregarding the fact that I have all the roles loaded in memory for the user. How can I avoid that? Is there a reason we couldn't make this the default?

https://github.com/RolifyCommunity/rolify#cached-roles-to-avoid-n1-issue

Here's the debugging output:

>  user.has_cached_role?(:staff, record)
true
>  user.roles.loaded?
true
>  user.has_role?(:staff, record)
  Role Exists? (0.6ms)  SELECT 1 AS one FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND "roles"."name" = $2 AND "roles"."resource_type" = $3 AND "roles"."resource_id" = $4 LIMIT $5  [["user_id", 3], ["name", "staff"], ["resource_type", "Entity"], ["resource_id", 21], ["LIMIT", 1]]
   (pry):3:in `show?'
true
>  user.has_role?(:staff, record)
  CACHE Role Exists? (0.0ms)  SELECT 1 AS one FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND "roles"."name" = $2 AND "roles"."resource_type" = $3 AND "roles"."resource_id" = $4 LIMIT $5  [["user_id", 3], ["name", "staff"], ["resource_type", "Entity"], ["resource_id", 21], ["LIMIT", 1]]
  ↳ (pry):4:in `show?'
true

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant