ruby on rails - Is there any way to access the parent object in a Cancan nested resource ability? -


i have nested resource i'm using cancan authorization. need able access parent object in order able authorize :index action of child (since no child instance passed :index action).

# memberships_controller.rb class membershipscontroller < applicationcontroller   ...   load_and_authorize_resource :org   load_and_authorize_resource :membership, through: :org   .. end 

ability.rb

can [:read, :write], membership |membership|   membership.org.has_member? user end 

this doesn't work :index action

unfortunately index action doesn't have membership instance associated , can't work way check permissions.

in order check permissions, need interrogate parent object (the org) , ask whether current user member e.g.

# ability.rb ... can :index, membership, org: { self.has_member? user } 

cancan lets me this...

cancan states can access parent's attributes using following mechanism: https://github.com/ryanb/cancan/wiki/nested-resources#wiki-accessing-parent-in-ability

# in ability can :manage, task, :project => { :user_id => user.id } 

however works comparing attributes doesn't work case.

how can access parent object though?

is there way access parent object within permissions?

i faced same problem , ended following (assuming have org model):

class membershipscontroller < applicationcontroller   before_action :set_org, only: [:index, :new, :create] # if shallow nesting enabled (see link @ bottom)   before_action :authorize_org, only: :index    load_and_authorize_resource except: :index    # orgs/1/memberships   def index     @memberships = @org.memberships   end    # ...  private    def set_org     @org = org.find(params[:org_id])   end    def authorize_org     authorize! :access_memberships, @org   end  end 

ability.rb:

can :access_memberships, org |org|   org.has_member? user end 

useful links

https://github.com/ryanb/cancan/issues/301

http://guides.rubyonrails.org/routing.html#shallow-nesting


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -