Search code examples
ruby-on-railsdeviserubygemscancanrolify

What's the point of Rolify and CanCan?


I'm working on a RoR project and I'm a little confused about this new gem that was recommended for my purposes, Rolify. As I understand it, rolify does pretty much the same thing as CanCan except it persists abilities (roles for rolify) to the database. However, all over the Rolify wiki, I see instructions on using Rolify with CanCan.

So basically, I'm wondering what's the difference between Rolify and CanCan? When should I use the one and not the other?


Solution

  • CanCan is used for managing authorization from the application standpoint is what lets you restrict X controller/action to X user.

    When you want to dive into a deeper fine grained of control you use Rolify. Rolify, goes beyond the simple

    if user.role == :super_admin
      # do something pretty cool stuff
    elsif user.role == :admin
      # do some more awesome stuff
    

    by allowing you to add roles to resources. Let's say you have a forum application, where you want an user to be able to have a moderator role on the Gaming Board. You would use rolify to by

    user = User.find(2)
    user.add_role :moderator, Forum.where(type: 'Gaming')
    

    Rolify also let's you do this to a class by using the class itself instead of an instance (in case you want an user to be a moderator of all the boards)

    user = User.find(2)
    user.add_role :moderator, Forum
    

    After that it lets you easily query the resources/class to find out who was access to what. On top of helping you manage the roles scope.