DEV Community

Cover image for Loading and Authorizing ActsAsTaggable tags using the Cancan authorization library
Robert Hustead
Robert Hustead

Posted on

Loading and Authorizing ActsAsTaggable tags using the Cancan authorization library

tl;dr (Too long, didn’t read)

class SomeController < ApplicationController
  load_and_authorize_resource class: ActsAsTaggableOn::Tag

  def index; end  #@tags is available in this action
  def show; end #@tag is available in this action
end

Explanation:

The Cancan library is very useful for controlling resources and what users are allowed to read, write, modify, or change them. Normally, when load_and_authorize_resource is included into a RESTful style Controller, it uses a before filter to load an instance variable into memory. However, things can get difficult if you want to load a resource from another class or if the model you wish to use is namespaced differently from the controller.

If you’re using ActsAsTaggableOn to add tags to some models in your app, you can still load those tags as a resource using the code above. From the Cancan documentation on github (https://github.com/ryanb/cancan/wiki/authorizing-controller-actions#custom-class)
“If the model class is namespaced differently than the controller you will need to specify the :class option.”

Remember to set your user abilities for accessing Tags in your abilities files when using Cancan!

Good luck, and happy coding!

Top comments (0)