我的 Rails 应用程序中有几个 Controller (UserController、PostController、SessionController 等...)
在所有每个操作之前,我想使用 gon gem. 传递一个 json 对象
我已将这行代码添加到我的应用程序帮助程序中:
module ApplicationHelper
...
def adding_gon
gon.signed_in = signed_in?
end
end
我还添加了可供所有 Controller 使用的 ApplicationHelper:
class ApplicationController < ActionController::Base
include ApplicationHelper
end
问题是现在我需要转到每个 Controller 并编写这行代码:
before_filter :adding_gon
将这行代码写入每个 Controller 相当重复。
有没有办法让这个方法在所有操作之前执行?
最佳答案
由于 Controller 通常继承自 ApplicationController
,因此您不必将 before_filter
添加到每个 Controller 。只需在 ApplicationController
的类定义中添加这一行,过滤器就会在所有子 Controller 操作之前执行,除非您是从其他 Controller 继承的。
关于ruby-on-rails - 如何使方法出现在所有 Controller 操作之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167777/