【问题标题】:Using Vanity URLs and CanCanCan gem (load_and_authorize_resource error)使用 Vanity URL 和 CanCanCan gem(load_and_authorize_resource 错误)
【发布时间】:2015-02-16 21:11:04
【问题描述】:

我正在尝试在我的 Rails 应用程序中使用 Vanity URL,以便显示用户名而不是 ID。我创建了 slug,以便在 url 中使用用户名而不是 id(这里一切正常),当我尝试加载在控制器中启用了 load_and_authorize_resource 的页面时,就会出现我面临的问题。我相信这是试图通过 id 而不是导致错误“找不到 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

【问题讨论】:

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


    【解决方案1】:

    我想通了;将 find_by: :slug 添加到 load_and_authorize_resource 正是我想要的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      相关资源
      最近更新 更多