从另一个控制器调用方法 [英] Calling a method from another controller

查看:53
本文介绍了从另一个控制器调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I've got a method in a different controller to the one I'm writing in, and I want to call that method, is it possible, or should I consider moving that method to a helper?

推荐答案

从技术上讲,您可以创建其他控制器的实例并在其上调用方法,但它很乏味,容易出错,强烈不推荐.

You could technically create an instance of the other controller and call methods on that, but it is tedious, error prone and highly not recommended.

如果该函数对两个控制器都是通用的,您可能应该在 ApplicationController 或您创建的另一个超类控制器中使用它.

If that function is common to both controllers, you should probably have it in ApplicationController or another superclass controller of your creation.

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

按照 jimworm 建议的另一种方法是使用模块来实现通用功能.

Yet another way to do it as jimworm suggested, is to use a module for the common functionality.

# 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

这篇关于从另一个控制器调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆