Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I had the same problem just the other day. I figured out the solution after reading the CanCan readme, which you should do if you haven't yet. </p> <p>You can view my solution here: <a href="https://stackoverflow.com/questions/7102351/context-aware-authorization-using-cancan/7117410">Context aware authorization using CanCan</a></p> <p>To give you an answer more specific to your use case, do the follow:</p> <p>In your application controller you need to define some logic which will pick your abilities.</p> <pre><code>class ApplicationController &lt; ActionController::Base check_authorization def current_ability if &lt;no group selected logic&gt; # Maybe: params[:controller] == 'groups' @current_ability = NoGroupSelectedAbility.new(current_user) else @current_ability = GroupSelectedAbility.new(current_user) end end # Application Controller Logic Below end </code></pre> <p>You'll then need to create a new ability (or abilities) in your app/models/ folder. You can also do cool stuff like this:</p> <pre><code>if request.path_parameters[:controller] == groups @current_ability = GroupsAbility.new(current_group_relation) end </code></pre> <p>Where current_group_relation is defined in app/controllers/groups_controller.rb. This will give you specific abilities for specific controllers. Remember that a parent classes can call methods in child classes in Ruby. You can define a method in your controller, and call it from ApplicationController, as long as you are certain what controller is currently being used to handle the request. </p> <p>Hope that helps.</p> <p>EDIT: I wanted to show you what a custom ability looks like. </p> <pre><code># File path: app/models/group_ability.rb class GroupsAbility include CanCan::Ability # This can take in whatever you want, you decide what to argument to # use in your Application Controller def initialize(group_relation) group_relation ||= GroupRelation.new if group_relation.id.nil? # User does not have a relation to a group can :read, all elsif group_relation.moderator? # Allow a mod to manage all group relations associated with the mod's group. can :manage, :all, :id =&gt; group_relation.group.id end end end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload