edg*_*ner 50
您可以在技术上创建另一个控制器的实例并在其上调用方法,但它是单调乏味,容易出错且非常不推荐.
如果该功能对于两个控制器都是通用的,那么您应该将它放在ApplicationController您创建的另一个超类控制器中.
class ApplicationController < ActionController::Base
def common_to_all_controllers
# some code
end
end
class SuperController < ApplicationController
def common_to_some_controllers
# some other code
end
end
class MyController < SuperController
# has access to common_to_all_controllers and common_to_some_controllers
end
class MyOtherController < ApplicationController
# has access to common_to_all_controllers only
end
Run Code Online (Sandbox Code Playgroud)
另一种方法是像jimworm建议的那样,使用模块来实现通用功能.
# lib/common_stuff.rb
module CommonStuff
def common_thing
# code
end
end
# app/controllers/my_controller.rb
require 'common_stuff'
class MyController < ApplicationController
include CommonStuff
# has access to common_thing
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44615 次 |
| 最近记录: |