如何让用户只使用cancan访问自己的显示页面?

时间:2011-06-12 18:15:19

标签: ruby-on-rails cancan

我一直在使用cancan gem进行railscast,但我仍坚持如何只允许用户访问他们自己的显示页面。

我的代码如下所示:

能力模型

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.role == "admin"
      can :manage, :all
    else
      can :read, :all
      if user.role == "author"
        can :create, Review
        can :update, Review do |review|
          review.try(:user) == user
        end
        can :update, User do |user|
          user.try(:current_user) == current_user
        end
      end
      if user.role == "owner"
        can :update, Venue
      end
    end
  end
end

用户控制器

class UsersController < ApplicationController
  load_and_authorize_resource
end

用户(作者)只能更新自己的评论,但目前可以通过更改网址查看所有用户的展示页面。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:11)

约束可以在你的能力等级中传递,甚至比你尝试的方式更容易。我确信这会缺少你想要的一些能力,但这应该让你开始。我假设评论:belong_to用户的外键为:user_id。它看起来你需要一些类似的场地约束,但你没有在你的代码中使用它,所以我没有把它放在这里。

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.role == "admin"
      can :manage, :all
    elsif user.role == "author"
      can :create, Review
      can :update, Review, :user_id => user.id
      can [:show, :update], User, :id => user.id
    elsif user.role == "owner"
      can :update, Venue
      can [:show, :update], User, :id => user.id
    else
      can [:show, :update], User, :id => user.id
    end
  end
end

答案 1 :(得分:0)

尝试在控制器中添加一个检查,以便在/ show的请求进入时检查current_user是否是页面/配置文件的所有者。有点像:

def show
  @user = User.find(params[:id])
  #show_page unless current_user.id != @user.id
end

可能会闪现一个“你没有拥有该页面”的通知或类似的失败。

相关问题