Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

ruby - Rails Devise: authenticate either two models

I'm building Rails app with three models for devise : Administrator, Teacher, Student. I would like to create a page that administrators and teachers can access.

I know how to create a page that users of one role can access. like

before_action :authenticate_model!

But how do I do when I would like to check the authentication of either administrator or teacher.

Auto redirect path can be fixed one. For example, if a user visited the page without logging in, the user will be redirected to teacher's login page with a hyperlink to administrator.

Any ideas?

question from:https://stackoverflow.com/questions/65897519/rails-devise-authenticate-either-two-models

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you can use the devise_group option.

Example:

inside BlogsController (or any other controller, it doesn't matter which):
  devise_group :blogger, contains: [:user, :admin]

Generated methods:
  authenticate_blogger!  # Redirects unless user or admin are signed in
  blogger_signed_in?     # Checks whether there is either a user or an admin signed in
  current_blogger        # Currently signed in user or admin
  current_bloggers       # Currently signed in user and admin

Use:
  before_action :authenticate_blogger!              # Redirects unless either a user or an admin are authenticated
  before_action ->{ authenticate_blogger! :admin }  # Redirects to the admin login page
  current_blogger :user                             # Preferably returns a User if one is signed in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...