使用个性化 URL 和 CanCanCan gem(load_and_authorize_resource 错误)
Using Vanity URLs and CanCanCan gem (load_and_authorize_resource error)
我正尝试在我的 Rails 应用程序中使用 Vanity URL,以便显示用户名而不是 ID。我创建了 slug,以便在 url 中使用用户名而不是 id(这里一切正常),当我尝试加载我有 [=16 的页面时,我面临的问题发生了=] 在控制器中启用。我相信这是试图通过 id 而不是导致错误 "Couldn't find User with id=X" 的 slug 找到用户。有什么地方我可以覆盖 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
我明白了;添加 find_by: :slug 到 load_and_authorize_resource 正是我想要的。
load_and_authorize_resource only: [:dashBoard], find_by: :slug
我正尝试在我的 Rails 应用程序中使用 Vanity URL,以便显示用户名而不是 ID。我创建了 slug,以便在 url 中使用用户名而不是 id(这里一切正常),当我尝试加载我有 [=16 的页面时,我面临的问题发生了=] 在控制器中启用。我相信这是试图通过 id 而不是导致错误 "Couldn't find User with id=X" 的 slug 找到用户。有什么地方我可以覆盖 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
我明白了;添加 find_by: :slug 到 load_and_authorize_resource 正是我想要的。
load_and_authorize_resource only: [:dashBoard], find_by: :slug