gpt4 book ai didi

ruby-on-rails - Rails - 从不同的 Controller 调用相同的 after_action 方法

转载 作者:行者123 更新时间:2023-12-04 06:28:57 25 4
gpt4 key购买 nike

登录后,我让 SessionsController 运行 after_action 来重置某些用户列。在另一个 Controller 中,我想在创建和更新时执行相同的 after_action。

将相同的代码复制并粘贴到两个 Controller 中很容易,但我知道有一天我会在一个 Controller 中进行更改而忘记更新另一个 Controller 。

有没有办法从不同的 Controller 调用与 after_action 相同的方法?

最佳答案

有几种方法可以做你想做的事:

  • 选项 1:在 ApplicationController 中定义一个方法并使用 after_action 调用此方法回调
  • 选项 2:在您的 lib/文件夹中定义一个模块,将其包含在 Controller 中并在 after_action 中调用其方法回调
  • 可能还有其他选项


  • 选项 1:ApplicationController 中的方法

    执行:
    class ApplicationController < ActionController::Base
    # ...

    def clean_user_columns
    raise 'No user connected!' unless current_user.present?
    do_some_stuff
    end

    用法:
    class SessionsController < ApplicationController
    after_action :clean_user_columns

    选项 2: Controller 中包含的模块

    执行:
    # file created here: /lib/clean_user_columns_after_action.rb
    # you will need to restart your server to see the changes of this file
    module CleanUserColumnsAfterAction
    def clean_user_columns
    do_some_stuff
    end
    end

    用法:
    class SessionController < ApplicationController
    include CleanUserColumnsAfterAction
    after_action :clean_user_columns

    结论:在我看来, 选项 #2 是要走的路:
  • 选项 #1 涉及您的 clean_user_columns 可用于您的应用程序的每个 Controller ,但它只会在调用时使用。与选项 #2 相比,它为您节省了一行代码,即 include CleanCleanUserColumnsAfterAction线。
  • 选项 #2 使您在要使用它的地方包含模块,而不是提供给应用程序的每个 Controller 。
  • 选项#2 可以通用化,并作为多个 Controller 共享代码片段的示例,例如从数据库中检索记录、执行特定操作(例如,如果用户不是管理员则重定向)等。您可以创建一个文件夹 lib/controllers/包含 Controller 的所有共享代码(如果是这样,不要忘记在模块定义 + Controllers::CleanUserColumnsAfterAction 语句中将模块重命名为 include)。
  • 选项 #2 涉及在 lib/中定义的文件,它不会像您的开发环境中的其他文件一样重新加载。这意味着在您的应用程序上测试您的新代码之前,您需要重新启动服务器。
  • 关于ruby-on-rails - Rails - 从不同的 Controller 调用相同的 after_action 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588995/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com