到目前为止,大多数的s听过的问题都与“有什么不同”有关。我需要知道如何在不同的控制器之间重用每个控制器。
下面只是一个例子。
ApplicationController:
private
def redirect
redirect_to welcome_path
end
任意控制器:
class AnyController < ApplicationController
before_action :redirect, only: :about
def about
end
end
现在,我有许多控制器使用相同的私有方法,并希望在一个中心位置存储它。你知道,让它保持干燥之类的。将这些私有方法放在哪里,以便在继承自ApplicationController的控制器之间重用?如果这样的问题已经回答了,请给我指点。谢谢。
发布于 2016-11-26 23:43:59
将这些私有方法放在哪里,以便在继承自ApplicationController的控制器之间重用?
如果您希望从ApplicationController
继承的类拥有该方法,则只需将其放入ApplicationController
中即可。
class ApplicationController < ActionController::Base
private
def redirect_to welcome_path
end
end
class AnyController < ApplicationController
# gets the redirect_to welcome_path method
end
这就是为什么ApplicationController
存在的原因。
Re:模块,它不需要在模块中,除非您最终想将它混合到ApplicationController
之外的另一个类中。
https://stackoverflow.com/questions/40816187
复制相似问题