我目前有一个已经很大的控制器.我想知道减少控制器的最佳方法是什么.我不一定在寻找最简单的方法,而是一种安全有效的方式.我一直在使用Rails开发一段时间,但我仍然不熟悉“子类化”的工作方式,我甚至不确定它是否应该以这种方式使用.我想也许是这样的?
- class SomeController < ApplicationController
- end
- class MoreFunctionsController < SomeController
- end
目前尚未经过测试 – 我现在仍在努力 – 但我希望这会让你知道我想去的方向.我也不确定这样的路由是什么样的.什么是“拆分”大型控制器的最佳方法?@H_502_5@
解决方法
ActiveSupport :: Concern
(documentation)正是您所需要的.
更新@H_502_5@
像这样的东西:@H_502_5@
- # config/application.rb
- config.autoload_paths += %W(#{Rails.root}/app/controllers/concerns) # in Rails4 this is automatic
- # app/controllers/my_controller.rb
- class MyController < ApplicationController
- include GeneralStuffConcern
- def index
- render text: foo
- end
- end
- # app/controllers/concerns/general_stuff_concern.rb
- module GeneralStuffConcern
- extend ActiveSupport::Concern
- def show
- redirect_to root_path
- end
- protected
- def foo
- 'fooo'
- end
- end
更新2@H_502_5@
我实际上推荐这更多http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/@H_502_5@