你如何用Devise保护控制器动作?

时间:2011-12-08 15:26:29

标签: ruby-on-rails ruby devise

我正在使用Devise,用户既可以是管理员也可以不是(真,假)。

有人可以帮我弄清楚如何保护控制器动作,例如:

  def new
    @post = Post.new
  end

我知道Devise允许您通过在视图中使用来调用管理员,但这可以在控制器中使用吗?:

if current_user.admin?

提前致谢。

1 个答案:

答案 0 :(得分:10)

您只需添加过滤器即可:

class YourController < ApplicationController
  before_filter :check_access, :only => :new

  ...

  def new
    @post = Post.new
  end

  protected
  def check_access
    redirect_to <whatever> and return unless current_user.admin?
  end
end

或使用CanCan或类似的东西来很好地保持限制