Ruby-on-rails 如何从 ApplicationHelper 调用 ApplicationController 方法

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

How to call ApplicationController methods from ApplicationHelper

ruby-on-railsrubyruby-on-rails-3controllerview-helpers

提问by David

I want to provide csv links in a view and I placed the csv generating code in ApplicationHelper. However I'm getting this error:

我想在视图中提供 csv 链接,并将 csv 生成代码放在ApplicationHelper. 但是我收到这个错误:

undefined method `send_data' for #<#<Class:0x0000010151c708>:0x0000010151a070>

referencing this:

参考这个:

send_data content, :type => "text/plain",
  :filename => filename,
  :disposition => 'attachment'

If I place the csv code in a controller it works fine. I was hoping to use the helper to avoid having to define routes for every controller I want to provide csv options for (I have a bunch). How can I make send_data(and other necessary methods) available to the helper?

如果我将 csv 代码放在控制器中,它就可以正常工作。我希望使用帮助程序来避免为我想为其提供 csv 选项的每个控制器定义路由(我有一堆)。我如何使send_data(和其他必要的方法)可供助手使用?

回答by Harish Shetty

Use helper_method.

使用helper_method.

By default, methods in ApplicationControllerare only accessible inside the Controllers.

默认情况下,方法ApplicationController只能在控制器内部访问。

Add a method to the ApplicationControllerand expose it as a helper method with helper_method:

向 中添加一个方法ApplicationController并将其作为辅助方法公开helper_method

class ApplicationController < ActionController::Base

  helper_method :foo

  def foo
    "bar"
  end

end

Now the foomethod is accessible to both Controllers andViews.

现在foo控制器视图都可以访问该方法。

回答by GeorgeW

If the issue is to make methods in ApplicationHelper available in all controllers, why not add a line

如果问题是让 ApplicationHelper 中的方法在所有控制器中可用,为什么不添加一行

include ApplicationHelper

to the ApplicationController file?

到 ApplicationController 文件?