在Controller中重构before_filters

发布于 2024-07-10 17:46:58 字数 714 浏览 10 评论 0原文

我正在开发一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你另情深 2024-07-17 17:46:58

将大量权限内容抽象到您的用户模型中(也许是标志?完整的权限模型和链接表可能有点过分,但也许不是)。 将当前登录的用户 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 a User.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文