使用虚荣URL和CanCanCan gem(load_and_authorize_resource错误)

时间:2015-02-16 21:11:05

标签: ruby-on-rails vanity-url cancancan

我试图在我的Rails应用中使用虚荣网址,以便显示用户名而不是ID。我创建了slug,以便在url中使用用户名而不是id(一切都在这里工作正常),当我尝试加载我启用了load_and_authorize_resource的页面时,我遇到的问题就出现了控制器。我相信这是试图通过id找到用户而不是导致错误的slug"找不到id = X"的用户。有没有我可以覆盖load_and_authorize_resource以便它使用slug而不是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

1 个答案:

答案 0 :(得分:1)

我明白了;将find_by :: slug添加到load_and_authorize_resource完全符合我的要求。

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