Lazy Load CanCanCan Abilities In Rails

Dale Zak
4 min readMar 17, 2021

This Rails strategy lets you lazy load your CanCanCan abilities so you only load them when needed helping improve overall performance.

I love CanCanCan, it’s a powerful authorization library for Rails initially created the Ryan Bates and later adopted by the Rails community to support and maintain. It’s my default authorization gem for all my Rails projects.

I also like to follow STI pattern for authentication, for example having a base User with Admin, etc subclasses. To go along with these user types, I usually define UserAbility, AdminAbility, etc to encapsulate all specific user’s abilities in one file.

This works great, although as a project grows these user ability files tend to get large. And if you are using any kind of _ids queries like user.post_ids when defining your abilities, you can see a performance hit since these query will be executed every time and not just when checking that specific ability.

So I recently to adopt the strategy outlined by Alessandro Rodi to separate abilities per model. For example where previously I had UserAbility or AdminAbility, I would now have PostAbility, CommentAbility, etc. However after implementing this pattern, I ran into a few problems so came up with some solutions.

Problem 1: If-Else Checks In Every Ability…

--

--

Dale Zak

Full stack developer specializing in web apps built on Rails with Stimulus, and mobile apps using Ionic and Vue.