Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify cancan load and authorize resource to load resource using different id

How can I modify load and authorize resources to load resource using different id. for ex.

my routes is

http://localhost:3000/organization/user/12/event/20/edit

and in my event controller I am accessing event using :event_id and user using :id

Now in my event controller how can I modify load_and_authorize_resource use :event_id instead of :id for loading an event

like image 319
Braham Shakti Avatar asked Feb 10 '23 10:02

Braham Shakti


2 Answers

The resource will only be loaded into an instance variable if it hasn't been already. This allows you to easily override how the loading happens in a separate before_filter.

class EventsController < ApplicationController
  before_filter :find_event
  load_and_authorize_resource

  private

  def find_event
    @event = Event.find(params[:event_id])
  end
end

Read more in the docs: https://github.com/CanCanCommunity/cancancan/wiki/Authorizing-controller-actions

like image 51
karlingen Avatar answered Feb 13 '23 16:02

karlingen


CanCan supports this through the id_param option:

From the documentation:

  # [:+id_param+]
  #   Find using a param key other than :id. For example:
  #
  #   load_resource :id_param => :url # will use find(params[:url])

Therefore you can do the following in your situation:

load_and_authorize_resource :id_param => :event_id
like image 27
cweston Avatar answered Feb 13 '23 17:02

cweston