简体   繁体   中英

Using Vanity URLs and CanCanCan gem (load_and_authorize_resource error)

I'm attempting to use Vanity URLs in my Rails app so that instead of an ID, the username is shown. I've created the slug so that the username is used in the url instead of the id (everything works here ok), the issue I'm facing occurs when I try to load a page where I have load_and_authorize_resource enabled in the controller. I believe this is attempting to find the user via the id instead of the slug which is causing the error "Couldn't find User with id=X". Is there somewhere I can override the load_and_authorize_resource so that it uses the slug and not the ID?

class User < ActiveRecord::Base

    def to_param
        slug
    end

end

class UsersController < ApplicationController 
    load_and_authorize_resource only: [:dashBoard]

    def dashboard

    end

    def show 
    #this is the user's profile page, because I don't have a load 
    #and authorize resource check on it, it loads without error 
    #when the vanity url is enabled

        @user = User.find_by_slug(params[:id])
    end

end

class Ability
    include CanCan::Ability  

    def initialize(user)
        user ||= User.new # guest user (not logged in)

        if user.memberships.count > 0
            can :manage, User           
        else
            can :read, :all
        end
    end
end

I figured it out; adding find_by: :slug to the load_and_authorize_resource did exactly what I was looking for.

load_and_authorize_resource only: [:dashBoard], find_by: :slug

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM