从另一个控制器调用方法

cjm*_*671 30 ruby-on-rails

如果我在一个不同的控制器中有一个方法,我正在编写的那个,我想调用那个方法,是否可能,或者我应该考虑将该方法移动到帮助器?

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)

  • 或者包含在`module`中. (5认同)