Ruby-on-rails 从另一个控制器调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8225518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:23:34  来源:igfitidea点击:

Calling a method from another controller

ruby-on-rails

提问by cjm2671

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?

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

回答by edgerunner

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.

从技术上讲,您可以创建另一个控制器的实例并在其上调用方法,但它很乏味、容易出错并且极不推荐。

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

如果该功能对两个控制器都是通用的,您可能应该在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

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

按照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

回答by Joseph Le Brech

Try and progressively move you methods to your models, if they don't apply to a model then a helper and if it still needs to be accessed elsewhere put in the ApplicationController

尝试逐步将您的方法移动到您的模型中,如果它们不适用于模型然后是一个助手,并且如果它仍然需要在 ApplicationController 中的其他地方访问

回答by zachar

I don't know any details of your problem, but maybe paths could be solution in your case (especially if its RESTful action).

我不知道您的问题的任何详细信息,但在您的情况下,路径可能是解决方案(特别是如果它的 RESTful 操作)。

http://guides.rubyonrails.org/routing.html#path-and-url-helpers

http://guides.rubyonrails.org/routing.html#path-and-url-helpers

回答by Rahul Goyal

If you requirement has to Do with some DB operations, then you can write a common function (class method) inside that Model. Functions defined inside model are accessible across to all the controllers. But this solution does to apply to all cases.

如果您需要做一些数据库操作,那么您可以在该模型中编写一个通用函数(类方法)。所有控制器都可以访问模型内​​部定义的函数。但是这个解决方案确实适用于所有情况。