48

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

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

参考这个:

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

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

4

2 回答 2

113

使用helper_method.

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

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

class ApplicationController < ActionController::Base

  helper_method :foo

  def foo
    "bar"
  end

end

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

于 2011-05-13T03:32:43.680 回答
10

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

包括 ApplicationHelper

到 ApplicationController 文件?

于 2011-05-29T16:07:39.870 回答