DEV Community

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

Posted on

3 2

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay