Rails:我应该如何在控制器之间共享逻辑?
这个问题肯定已经被问到了,但我找不到了。
我有一个UsersController
和一个Admin::UsersController
。 显然,这些类中发生的很多事情(例如, strong_parameters
的实现,创建/编辑用户后要遵循的路径)是相同的。
我可以 – 的确,我应该吗? – 在这些控制器之间共享代码? 这是关注的问题吗? 我在网上找到的例子往往涉及模型。
任何指导非常感谢。
使用顾虑(放入app/controllers/concerns
)
module UsersControllable extend ActiveSupport::Concern def new end def create end private def user_params # strong params implementation end end class UsersController < ApplicationController include UsersControllable end class Admin::UsersController < ApplicationController include UsersControllable end
一种方法是使用inheritance。 创建一个新的控制器:
class SharedUserController < ApplicationController # With shared code end
然后:
class UsersController < SharedUserController end class Admin::UsersController < SharedUserController end
希望这有帮助!