1

我使用deviseand cancangems 并且有简单的模型关联:user has_many subscriptions, subscription belongs_to :user. 有以下SubscriptionsController

class SubscriptionsController < ApplicationController

  load_and_authorize_resource :user
  load_and_authorize_resource :subscription, through: :user

  before_filter :authenticate_user!

  def index
    @subscriptions = @user.subscriptions.paginate(:page => params[:page]).order(:created_at)
  end

  #other actions
end

并且Cancan Ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)

    user ||=User.new

    can [:read], [Edition, Kind]

    if user.admin?
      can :manage, :all
    elsif user.id
      can [:read, :create, :destroy, :pay], Subscription, user_id: user.id
      can [:delete_from_cart, :add_to_cart, :cart], User, id: user.id
    end

  end

end

问题是我不能subscriptions以用户身份使用操作,但可以以管理员身份使用。并且没有问题UsersController。当我从以下行中删除SubscriptionsController

  load_and_authorize_resource :user
  load_and_authorize_resource :subscription, through: :user

  before_filter :authenticate_user!

完全没有问题。所以问题在这些行或Ability.rb. 有什么建议么?

更新:有趣的是,如果我将 smth like 添加can? :index, Subscription到 html 模板中,它会显示true. 如果添加 smth like can? :index, Subscription.first(另一个用户的订阅),它会显示false. 看起来Cancan工作正常。但是有什么问题吗?...

更新:如果更改SubscriptionsControlle如下:

class SubscriptionsController < ApplicationController

  #load_and_authorize_resource :user
  #load_and_authorize_resource :subscription, through: :user

  before_filter :authenticate_user!

  def show
    @user = User.find params[:user_id] #line 1
    @subscription = @user.subscriptions.find params[:id] #line 2
    @container_items = @subscription.container_items.paginate(:page => params[:page])
    authorize! :show, @subscription #line 4
  end

  #some actions
end

它可以完美运行,并在需要时防止未经授权的用户访问。第 1 行、第 2 行和第 4 行是否不等于已注释?

更新:有以下内容routes.rb

resources :users, except: [:show] do
    member do
      get 'cart'
      delete 'delete_from_cart' => 'users#delete_from_cart'
      post 'add_to_cart' => 'users#add_to_cart'
    end
    resources :subscriptions do
      member do
        post 'pay'
      end
    end
  end

更新:下一个解决方案防止未经授权访问所有订阅操作,除了index

class SubscriptionsController < ApplicationController

  load_resource :user
  load_resource :subscription, through: :user
  authorize_resource through: :current_user

  before_filter :authenticate_user!

  #actions
end

那么阻止访问index操作的最佳方法是什么?

仅找到以下解决方案:

  before_filter :authorize_index, only: [:index]

  def authorize_index
    raise CanCan::AccessDenied unless params[:user_id] == current_user.id.to_s
  end
4

1 回答 1

1

它应该是

load_and_authorize_resource :subscription

要不就

load_and_authorize_resource

在你的情况下,当你想要嵌套资源时,然后

load_and_authorize_resource :through => :current_user

https://github.com/ryanb/cancan/wiki/Nested-Resources

于 2012-07-08T16:07:03.860 回答