在哪里放置 Rails 控制器的 Ruby 辅助方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13613223/
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-02 21:05:57  来源:igfitidea点击:

Where to put Ruby helper methods for Rails controllers?

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.2view-helpers

提问by at.

I have some Ruby methods certain (or all) controllers need. I tried putting them in /app/helpers/application_helper.rb. I've used that for methods to be used in views. But controllers don't see those methods. Is there another place I should put them or do I need to access those helper methods differently?

我有某些(或所有)控制器需要的 Ruby 方法。我试着把它们放进去/app/helpers/application_helper.rb。我已经将它用于要在视图中使用的方法。但是控制器看不到这些方法。是否还有其他地方我应该放置它们,或者我是否需要以不同的方式访问这些辅助方法?

Using latest stable Rails.

使用最新的稳定 Rails。

回答by Ryan Bigg

You should define the method inside ApplicationController.

你应该在里面定义方法ApplicationController

回答by John Cleary

For Rails 4 onwards, concerns are the way to go. There is a decent article here http://richonrails.com/articles/rails-4-code-concerns-in-active-record-models

对于 Rails 4 以后,关注是要走的路。这里有一篇不错的文章 http://richonrails.com/articles/rails-4-code-concerns-in-active-record-models

In essence, if you look in your controllers folder you should see a concerns sub-folder. Create a module in there along these lines

本质上,如果您查看您的控制器文件夹,您应该会看到一个关注子文件夹。沿着这些线在那里创建一个模块

module EventsHelper
  def do_something
  end
end

Then, in the controller just include it

然后,在控制器中只包含它

class BadgeController < ApplicationController
  include EventsHelper

  ...
end

回答by Muhamamd Awais

you should define methods inside application controller, if you have few methods then you can do as follow

您应该在应用程序控制器中定义方法,如果您的方法很少,那么您可以执行以下操作

class ApplicationController < ActionController::Base    
  helper_method :first_method
  helper_method :second_method

  def first_method
    ... #your code
  end

  def second_method
    ... #your code
  end
end

You can also include helper files as follow

您还可以包含帮助文件如下

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
end

回答by David

You can call any helper methods from a controller using the view_context, e.g.

您可以使用view_context,例如从控制器调用任何辅助方法

view_context.my_helper_method

回答by hyperrjas

Ryan Bigg response is good.

Ryan Bigg 的反应很好。

Other possible solution is add helpers to your controller:

其他可能的解决方案是向您的控制器添加助手:

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
 end

Best Regards!

此致!

回答by Aparichith

Including helpers in controller will end-up exposing helper methods as actions!

在控制器中包含 helper 最终会将 helper 方法暴露为操作!

# With new rails (>= 5) 

helpers.my_helper_method


# For console

helper.my_helper_method