DEV Community

loading...

CanCanCan 3.2.0

coorasse profile image Alessandro Rodi ・2 min read

Hi all πŸ‘‹,
a new version of CanCanCan is out!

Again, we have a minor release but it includes a bunch of very important features, next to support for Rails 6.1.0.

I have opened a sponsorship program, please consider supporting the project if you use CanCanCan. It really helps!

Switching query strategy

Since version 3.0.0 we started changing the way we perform the queries when using accessible_by, in order to be more performant and reliable.

As expected, this new way of performing the queries didn't fit everyone, so in version 3.1.0 we switched from left_joins to subqueries (see relevant PR).

This again didn't make everyone happy πŸ˜ƒ , so we decided, in the version 3.2.0 to allow to configure the preferred query mechanism: left joins or inner queries.

You can now setup:

CanCan.accessible_by_strategy = :subquery # or :left_join
Enter fullscreen mode Exit fullscreen mode

to change it.

Support for Single Table Inheritance

Single Table Inheritance is now supported. Given the following:

class Vehicle < ApplicationRecord

class Car < Vehicle

class Motorbike < Vehicle
Enter fullscreen mode Exit fullscreen mode

You can play with rules by defining:

can :read, Vehicle
Enter fullscreen mode Exit fullscreen mode

and query for:

Vehicle.accessible_by
# or
Motorbike.accessible_by
Enter fullscreen mode Exit fullscreen mode

Here is an example:

can :read, Motorbike

Vehicle.accessible_by(...) # => returns only motorbikes
Enter fullscreen mode Exit fullscreen mode

Check the relevant PR for more examples and note that there are currently some minor issues

Support for associations in rules definition

When using associations in rules definition you always had to use column names. Now, thanks to this PR you can also use the association name.

# previously you had to define:
can :edit, Book, author_id: user.id

# now you can also write:
can :edit, Book, author: user
Enter fullscreen mode Exit fullscreen mode

Enjoy! And to the next one...

Discussion (3)

pic
Editor guide
Collapse
yarotheslav profile image
Yaroslav Shmarov

Great job Alessandro & team! It feels like yesterday I was watching Ryan Bates presenting CanCan; than the move to CanCanCan. And now, 3.2!
IMHO one of the 2 best Authorization gems for Rails (alongside Pundit)

Collapse
jaredcwhite profile image
Jared White

Awesome, glad to see this library continuing to move forward. :+1

Collapse
sudhansubedi profile image
Madhu Sudhan Subedi

Thanks for the article! I have one question does this gem support for ruby version 3.0.0? I tried with ruby 3.0.0 and it shows me cancancan gem is not compatible for ruby version 3.0.0.