且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails_admin:我应该具有管理员角色的admin_user或用户来管理用户和管理面板

更新时间:2023-11-30 16:01:16

好问题。我在我的项目中使用Rails Admin和Pundit。



我喜欢拥有与用户模型分离的管理模式。





管理模型可以超级简单。生成
rails generate devise Admin



然后在你的 config / initializers / rails_admin.rb add

config.authenticate_with do
warden.authenticate! :scope => :admin
end
config.current_user_method(&:current_admin)



要重定向到正确的配置文件,将此方法添加到您的ApplicationController

def after_sign_in_path_for(资源)
如果resource.class == Administrator
rails_admin_path
else
#将profile_path更改为要定期用户去的地方
stored_location_for(resource)|| profile_path
end
end



为了防止退出当前管理员登出从当前用户设置此配置 config / initializers / devise.rb

config.sign_out_all_scopes = false



为了解决您的其他问题,我使用了CanCan和Pundit。我喜欢Pundit更好,因为CanCan对每个请求都评估所有的权限。使用Pundit,仅在需要时才会检查权限。 Pundit在我的经验中也更加灵活。


In my rails application website visitors can sign up and create content. It uses devise with user model and everything works well.

Now I want to use rails_admin for managing website resources and users etc and only people with administrative previllages should be able to access it.

Should I create a separate AdminUser model for admin panel access or use User model with role of admin, and use some authorization library to manage access.

If I user only one model then I want users to be redirected to admin panel after signin if user is admin and if not then I want user to be redirected to their profile. And which authorization library cancan or pundit will be more suitable in my case.

Thanks!

Good question. I use Rails Admin and Pundit in my project.

I prefer having an Admin model separate from the User model.

One reason is that I like to be able to "Become a user" from Rails Admin to be able to help them when they have an issue. Its easier to do when you have separate User and Admin models.

The Admin model can be super simple. Generate it with rails generate devise Admin

Then in your config/initializers/rails_admin.rb add config.authenticate_with do warden.authenticate! :scope => :admin end config.current_user_method(&:current_admin)

To redirect to the correct profile, add this method to your ApplicationController def after_sign_in_path_for(resource) if resource.class == Administrator rails_admin_path else # Change profile_path to where you want regular users to go stored_location_for(resource) || profile_path end end

In order to prevent signing out from the current Admin when signing out from the current User, set this configuration in config/initializers/devise.rb config.sign_out_all_scopes = false

To address your other question, I have used both CanCan and Pundit. I like Pundit better because with CanCan all the permissions are evaluated for each request. With Pundit, permissions are only checked when needed. Pundit is also more flexible in my experience.