Defining abilities through polymorphic association #939

mattangriffel opened this Issue Sep 19, 2013 · 2 comments


None yet
2 participants

I'm trying to define a user's ability to access something based on a column on an associated model, the problem is that it's a polymorphic association.

I've got steps, and each step has a steppable (either a lecture, a quiz, or some other action). I need an activerecord query that will work.

Of course can :read, Step, 'steppable' => {published: true} won't work since steppable isn't a table.

I've also tried joins and includes through a scope on step, like scope :published, includes(:steppable).where('steppable' => {published: true}) but that doesn't work because Rails can't eagerly load the polymorphic association.

Any advice here?

graywh commented Sep 20, 2013

Try adding the permissions one type at a time.

# app/models/step.rb
belongs_to :steppable_a, :class => SteppableA
belongs_to :steppable_b, :class => SteppableB

# app/models/ability.rb
can :read, Step, { :steppable_a => { :published => true } }
can :read, Step, { :steppable_b => { :published => true } }

Edit: Actually, you might have to make associations for each type of steppable and use those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment