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

Is there a way to query a role by model class and resource id, instead of running a query for the resource? #454

Open
ndbroadbent opened this issue Jun 30, 2017 · 1 comment

Comments

@ndbroadbent
Copy link

ndbroadbent commented Jun 30, 2017

For instance, I want to find out if the user is an admin of a certain company:

2.3.3 :035 > user.has_role? :admin, user.company
  Company Load (0.4ms)  SELECT  "companies".* FROM "companies" WHERE 
"companies"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
  Role Load (0.8ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" 
ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 
AND ((((roles.name = 'admin') AND (roles.resource_type IS NULL) 
AND (roles.resource_id IS NULL)) OR ((roles.name = 'admin') 
AND (roles.resource_type = 'Company') AND (roles.resource_id IS NULL)) 
OR ((roles.name = 'admin') AND (roles.resource_type = 'Company') 
AND (roles.resource_id = 3))))  [["user_id", 6]]
 => true

That first query is a waste, since I don't always need to look up the company. Is there a way that I achieve something like the following?

2.3.3 :035 > user.has_role? :admin, Company, user.company_id

I want to avoid the user.company call that hits the database, because the role lookup only needs to know about Company and user.company_id.

The above example gives the following error:

ArgumentError: wrong number of arguments (given 3, expected 1..2)

So this would be a non-breaking change if it was implemented.

@penguin-jedi
Copy link

OMG, I'm looking for this too. But a year ago.
So, I end up with a trick like this
user.has_role? :admin, Company.new(id: user.company_id)

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

2 participants