How to apply abilities to a non-restful controller in cancan

I'm new to rails and for the life of me I don't "get" cancan.

I've read this tutorial but can't figure out how to apply instructions to my situation.

In the cancan wiki there is:

  • an AdminController
  • a roll_logs action

In the ability class is says:

can :roll, :logs if user.admin?

I don't get what the :roll and :logs symbols have to do with the controller and the action?

All I want to do is say, if a user is an admin, give them access to the AdminController actions, otherwise don't, is this possible?

Answers


Yes this is possible.

The statement

can :roll, :logs if user.admmin?

means that when calling authorize! :roll, :logs an unauthorized exception gets thrown if the user isn't an admin.

So it doesn't have anything to do with a controller or an action, untill you make it so.

If you have a logs_controller for example with an action roll you could do something like this.

class LogsController < ApplicationController

  def roll
    authorize! :roll, :logs

    # Rest of the roll functionality.
  end

So in your example, you want to give users who are admin permission to access all admin controller actions.

You can achieve this like this.

ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    can(:manage, :admin) if user.admin?
  end
end

admin_controller.rb

class AdminController < ApplicationController

 authorize_resource :class => false

 def foo
 end

 def bar
 end

end

This will make sure that only admins can access the foo and bar actions of the admin_controller.

The :class => false statement means that you are not authorizing a resource, which is what we want since you are not for example authorizing a certain post or comment. You are just authorizing actions on a controller.


Need Your Help

How to use macros for concise, type-safe, unboxed enum?

scala enums metaprogramming value-type scala-macros

I am learning Scala macros and thinking of this as an exercise.

How to get selected text from WPF Combobox?

c# wpf xaml

I am trying to get text from WPF ComboBox, when it will select but unable to get any text. Below are the codes which I have tried. If someone please help me to get text from ComboBox when I select

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.