Skip to content

Implements the has_cached_role? method to prevent N+1 issues - #369

Merged
wldcordeiro merged 1 commit into
RolifyCommunity:masterfrom
gabrielhilal:has_cached_role
Nov 6, 2015
Merged

Implements the has_cached_role? method to prevent N+1 issues#369
wldcordeiro merged 1 commit into
RolifyCommunity:masterfrom
gabrielhilal:has_cached_role

Conversation

@gabrielhilal

Copy link
Copy Markdown
Contributor

This method will take the preloaded roles and use ruby enumerable to check if user has the role without extra queries.

e.g:

@user.add_role :admin, Forum
@user.add_role :member, Forum

users = User.with_role(:admin, Forum).preload(:roles)
users.each do |user|
  user.has_cached_role?(:member, Forum) # no extra queries
end

@gabrielhilal

Copy link
Copy Markdown
Contributor Author

#359

@gabrielhilal
gabrielhilal force-pushed the has_cached_role branch 2 times, most recently from b4a99c5 to a9afe74 Compare November 4, 2015 17:11
```ruby
@user.add_role :admin, Forum
@user.add_role :member, Forum

users = User.with_role(:admin, Forum).preload(:roles)
users.each do |user|
  user.has_cached_role?(:member, Forum) # no extra queries
end
```

This method should be used with caution. If you don't preload the roles, the `has_cached_role?` might return `false`. In the above example, it would return `false` for `@user.has_cached_role?(:member, Forum)`, because `User.with_role(:admin, Forum)` will load only the `:admin` roles.
wldcordeiro added a commit that referenced this pull request Nov 6, 2015
Implements the has_cached_role? method to prevent N+1 issues
@wldcordeiro
wldcordeiro merged commit 1359f6f into RolifyCommunity:master Nov 6, 2015
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

Successfully merging this pull request may close these issues.

2 participants