在Controller中重构before_filters
我正在开发一个 Rails 应用程序,该应用程序在 users_controller 中有一大堆 before 过滤器,这些过滤器查找由“充当状态机”提供的用户有状态角色。 它们看起来像这样:
class UsersController < ApplicationController
before_filter :not_logged_in_required, :only => [:new, :create]
before_filter :find_user_or_current_user, :only => [:edit, :update]
before_filter :find_user, :only => [:suspend, :unsuspend, :destroy, :purge]
before_filter :admin_required, :only => [:suspend, :unsuspend, :destroy, :purge]
before_filter :check_administrator_role, :only [:index, :suspend, :destroy, :purge]
通过对 UsersController 控制的每个操作进行状态检查,性能正在成为一个问题,对用户列的 SQL 查询在我的机器上花费了 5 毫秒以上。
我只是假设所有这些过滤器都在拖动性能中发挥作用,并且我想知道如何最好地重构这些过滤器以改善从数据库的读取。
I'm working on a rails app that has a whole bunch of before filters in the users_controller which look up user's stateful roles provided by Acts as State Machine.
They look something like this:
class UsersController < ApplicationController
before_filter :not_logged_in_required, :only => [:new, :create]
before_filter :find_user_or_current_user, :only => [:edit, :update]
before_filter :find_user, :only => [:suspend, :unsuspend, :destroy, :purge]
before_filter :admin_required, :only => [:suspend, :unsuspend, :destroy, :purge]
before_filter :check_administrator_role, :only [:index, :suspend, :destroy, :purge]
With all of this checking of states for each action controlled by the UsersController, performance is becoming an issue, with SQL queries to the Users Column taking upwards of 5ms on my machine.
I'm only assuming all of these filters play a part in the dragging performance, and I'm wondering how to best refactor these to improve the reading from the database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将大量权限内容抽象到您的用户模型中(也许是标志?完整的权限模型和链接表可能有点过分,但也许不是)。 将当前登录的用户 ID(可能还有其他一些常用的东西)存储到会话中。 留下一个名为
:auth
的 before_filter,它会执行User.find(session[:user_id])
并设置一些众所周知的类变量,可能是@loggedinuser
,到用户对象。 然后,您在@loggedinuser
上查找权限。Abstract a lot of the privilege stuff into your Users model (flags, perhaps? A full Privilege model and linktable might be overkill, but maybe not). Store the currently-logged in user's ID (and maybe a couple of other often-used things) into a session. Leave one before_filter, called
:auth
, that does aUser.find(session[:user_id])
and sets some well-known class variable, maybe@loggedinuser
, to the User object. Then you do lookups on the@loggedinuser
for privileges.