0

I have a User model generated by Devise. So, I have before filter authenticate_user.

I have used STI and created 2 more models UserA < User, UserB < User.

User has a field 'type' which determines whether user object is of type 'UserA' or 'UserB'.

I have some controllers in which I want specific filter, like, can be seen only by user type 'UserA' or UserB. So, I want to write a filter like this:

def authenticate_usera
    if current_user.type == 'usera'
        return true
    else
        return false
end

def authenticate_userb
    if current_user.type == 'userb'
        return true
    else
        return false
end

Question:
So, where should I place this filter code? And, can I use like this in controller:
before_filter :authenticate_usera

Also, do I need to use anything like 'require' for that filter to be available in this ?

4

1 回答 1

0

在您ApplicationController添加以下功能:

def only_allowed_for(user_type_class)
  unless current_user.is_a?(user_type_class)
    redirect_to root_path, :notice => 'Access to the page is not allowed'
  end
end

在我的测试中,我假设通过 STI,当前用户将拥有正确的课程。我对此并不完全确定(这可能取决于设计如何创建用户)。但你明白了。

然后,在任何控制器中,您可以编写以下内容:

class PostsController < ApplicationController

  before_filter :authenticate_user!
  before_filter { |c| c.only_allowed_for(UserA) }

end

如您所知:您可以编辑允许访问的类。如果不允许访问,这将重定向到 root。

于 2013-09-16T21:05:20.140 回答