Muhammad Usman
Muhammad Usman

Reputation: 358

Rails cancancan gem with sequenced gem

Building rails app. I am using cancancan for authorization and sequenced gem for using sequence number instead of real ID's. (For nice urls and simpler ID's). Now when the url is e.g.

/customers/1

Cancancan is loading customer with ID=1 instead of loading customer with Sequence_Number=1. How to tell cancancan to map params[:id] to sequence number instead of ID?

Upvotes: 0

Views: 104

Answers (1)

max
max

Reputation: 102203

Use the find_by option:

load_resource find_by: :sequence_number
authorize_resource

Or override CanCanCan's loading:

class ApplicationController
  MEMBER_ACTIONS = [:show, :edit, :update, :destroy]
  COLLECTION_ACTIONS = [:index, :new, :create]
end

class CustomersController < ApplicationController
  before_action :find_customer, only: MEMBER_ACTIONS
  load_and_authorize_resource

  def find_customer
    @customer = Customer.find_by!(sequence_number: params[:id])
  end 
end

CanCanCan will look at the controller name and try to load a model based on the name. It loads the model into an ivar with the singular name.

MovieDirectorsController ->  MovieDirector.find -> @movie_director

If the ivar already has a value then load_resource is skipped.

Upvotes: 1

Related Questions