Using CanCanCan With StimulusReflex In Your Rails App

Dale Zak
3 min readMar 23, 2021

If you are using CanCanCan for authorization and also want to use the magic of StimulusReflex for reactive page updates, these strategies will help you check user abilities in your reflexes.

CanCanCan is a powerful authorization library that allows you to authorize! the current_user for an action, as well as restrict records only accessible_by their current_ability.

def index
authorize! :index, Classroom
@classroom = Classroom.accessible_by(current_ability)
end

Once you start using StimulusReflex, you’ll soon need to utilize the accessible_by in your reflexes to only obtain records permitted for the current_user as well. The following are strategies how to do this for both selector morphs and page morphs.

Selector Morphs With CanCanCan

For selector morphs, you have two options for using CanCanCan’s accessible_by in your reflex.

Option 1: create new ability for user

First delegate the current_user to your connection, then create a new ability passing that into the accessible_by call.

class ClassroomsReflex < ApplicationReflex
delegate :current_user, to: :connection
def change_school
if…

--

--

Dale Zak
Dale Zak

Written by Dale Zak

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

No responses yet