Ruby-on-rails Rails - 如何在控制器中使用助手

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

Rails - How to use a Helper Inside a Controller

ruby-on-railsruby-on-rails-3ruby-on-rails-5

提问by AnApprentice

while I realize your are supposed to use a helper inside a view, I need a helper in my controller as I'm building a JSON object to return.

虽然我意识到您应该在视图中使用助手,但我需要在控制器中使用助手,因为我正在构建要返回的 JSON 对象。

It goes a little like this:

它有点像这样:

def xxxxx

   @comments = Array.new

   @c_comments.each do |comment|
   @comments << {
     :id => comment.id,
     :content => html_format(comment.content)
   }
   end

   render :json => @comments
end

how can I access my html_formathelper?

我如何访问我的html_format助手?

采纳答案by Xavier Holt

Note:This was written and accepted back in the Rails 2 days; nowadays grosser's answeris the way to go.

注意:这是在 Rails 2 天后编写并接受的;如今,格罗斯的答案是要走的路。

Option 1:Probably the simplest way is to include your helper module in your controller:

选项 1:可能最简单的方法是在控制器中包含辅助模块:

class MyController < ApplicationController
  include MyHelper

  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2:Or you can declare the helper method as a class function, and use it like so:

选项 2:或者您可以将辅助方法声明为类函数,并像这样使用它:

MyHelper.html_format(comment.content)

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

如果您希望能够将它用作实例函数和类函数,您可以在您的助手中声明这两个版本:

module MyHelper
  def self.html_format(str)
    process(str)
  end

  def html_format(str)
    MyHelper.html_format(str)
  end
end

Hope this helps!

希望这可以帮助!

回答by grosser

You can use

您可以使用

  • helpers.<helper>in Rails 5+(or ActionController::Base.helpers.<helper>)
  • view_context.<helper>(Rails 4 & 3) (WARNING: this instantiates a new view instance per call)
  • @template.<helper>(Rails 2)
  • include helper in a singleton class and then singleton.helper
  • includethe helper in the controller (WARNING: will make all helper methods into controller actions)
  • helpers.<helper>Rails 5+(或ActionController::Base.helpers.<helper>)中
  • view_context.<helper>( Rails 4 & 3) (警告:每次调用都会实例化一个新的视图实例)
  • @template.<helper>(导轨 2)
  • 在单例类中包含助手,然后 singleton.helper
  • include控制器中的帮助程序(警告:将所有帮助程序方法转换为控制器操作)

回答by Gerry Shaw

In Rails 5 use the helpers.helper_functionin your controller.

在 Rails 5 中,helpers.helper_function在您的控制器中使用 。

Example:

例子:

def update
  # ...
  redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
end

Source: From a comment by @Markus on a different answer. I felt his answer deserved it's own answer since it's the cleanest and easier solution.

来源:来自@Markus 对不同答案的评论。我觉得他的回答值得自己回答,因为它是最干净、最简单的解决方案。

Reference: https://github.com/rails/rails/pull/24866

参考:https: //github.com/rails/rails/pull/24866

回答by Thadeu Esteves Jr.

My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:

我的问题通过选项 1 解决了。可能最简单的方法是在控制器中包含辅助模块:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...

回答by Franco

In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController.

通常,如果要在(仅)控制器中使用帮助程序,我更愿意将其声明为class ApplicationController.

回答by Ravistm

In Rails 5+ you can simply use the function as demonstrated below with simple example:

在 Rails 5+ 中,您可以简单地使用以下简单示例演示的函数:

module ApplicationHelper
  # format datetime in the format #2018-12-01 12:12 PM
  def datetime_format(datetime = nil)
    if datetime
      datetime.strftime('%Y-%m-%d %H:%M %p')
    else
      'NA'
    end
  end
end

class ExamplesController < ApplicationController
  def index
    current_datetime = helpers.datetime_format DateTime.now
    raise current_datetime.inspect
  end
end

OUTPUT

"2018-12-10 01:01 AM"

输出

"2018-12-10 01:01 AM"

回答by albertm

class MyController < ApplicationController
    # include your helper
    include MyHelper
    # or Rails helper
    include ActionView::Helpers::NumberHelper

    def my_action
      price = number_to_currency(10000)
    end
end

In Rails 5+ simply use helpers(helpers.number_to_currency(10000))

在 Rails 5+ 中,只需使用助手helpers.number_to_currency(10000)