gpt4 book ai didi

ruby-on-rails - 在多个 Controller 中使用相同的 `before_action` 过滤器

转载 作者:行者123 更新时间:2023-12-05 08:51:30 24 4
gpt4 key购买 nike

在 Rails 应用程序中,我有一个发送 webhook 消息的 before_action 过滤器。由于我有几个 Controller ,我希望 before_action 对其执行操作,是否有一种好的方法可以使其成为一个模块并添加到它前面?

我目前的逻辑是:

# first_controller.rb:
before_action :do_something
def do_something
#same logic
end

# second_controller.rb:
before_action :do_something
def do_something
#same logic
end

# third_controller.rb:
before_action :do_something
def do_something
#same logic
end

最佳答案

如果您的 Controller 继承自 ApplicationController,您可以执行以下操作:

class ApplicationController < ActionController::Base
def do_something
#same logic
end
end

class FirstController < ApplicationController
before_action :do_something
end
class SecondController < ApplicationController
before_action :do_something
end
class ThirdController < ApplicationController
before_action :do_something
end

或者您可以创建自己的父 Controller ,例如。 DoSomethingController

class DoSomethingController < ApplicationController
before_action do_something

def do_something
#same logic
end
end

class FirstController < DoSomethingController
end
class SecondController < DoSomethingController
end
class ThirdController < DoSomethingController
end

或者您可以使用@code_aks 的回答 https://stackoverflow.com/a/59846330/8554172制作一个模块并包含它。

关于ruby-on-rails - 在多个 Controller 中使用相同的 `before_action` 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59844593/

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