如何将中间件与rails结合使用



我的系统中有3个角色,我想为每个角色创建中间件

我使用rake middleware,但这个命令创建了很多中间件,我想创建自己的中间件并在代码中使用它。

在rails中使用中间件的最佳方式是什么??

我认为过滤器相当于中间件。如果希望每次都运行一个方法,可以向ApplicationController添加一个before_action。或者,您只能添加到特定的控制器以优化性能。

我的建议是,阅读Rails指南来弄清楚这一点。https://guides.rubyonrails.org/action_controller_overview.html#filters

创建方法来检查用户的角色

def authorize_user
if(@user.user_type_id != 1)
render json:{'error': "user is un authorized to this page"} ,status:409
return
end
end

并获取方法before_action :authenticate_user

最新更新