如何使用cancan允许用户仅访问自己的展示页面?

7

我一直在学习使用cancan宝石的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

一个用户(作者)只能更新自己的评论,但是目前可以通过修改URL查看所有用户的展示页面。
我这里漏掉了什么?

1
问题出在 can :read, :all 这一行。你允许所有用户查看所有页面。 - mirelon
2个回答

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

0
尝试在控制器中添加一个检查,以便当请求 /show 时,检查当前用户是否是页面/个人资料的所有者。类似以下内容:
def show
  @user = User.find(params[:id])
  #show_page unless current_user.id != @user.id
end

如果失败,可以闪现一个通知,例如“您不拥有该页面”。


不需要这样做。CanCan可以为您完成所有这些工作。 - mirelon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接