Rails:我应该如何在控制器之间共享逻辑? [英] Rails: how should I share logic between controllers?
本文介绍了Rails:我应该如何在控制器之间共享逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题肯定已经有人问过了,但我找不到.
This question must have been asked already, but I can't find it.
我有一个 UsersController
和一个 Admin::UsersController
.显然,这些类中发生的很多事情(例如,strong_parameters
的实现,创建/编辑用户后要遵循的路径)是相同的.
I have a UsersController
and an Admin::UsersController
. Obviously a lot of what goes on in these classes (eg the implementation of strong_parameters
, the paths to follow after creating/editing a user) are the same.
我可以 - 确实,应该吗?- 在这些控制器之间共享代码?这是担心的原因吗?我在网上为他们找到的例子倾向于处理模型.
Can I - indeed, ought I? - share code between these controllers? Is this what concerns are for? The examples I find for them online tend to deal with models.
非常感谢任何指导.
推荐答案
使用关注点(放入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
这篇关于Rails:我应该如何在控制器之间共享逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文