How to call ApplicationController methods from ApplicationHelper

浪尽此生 提交于 2019-12-03 05:23:52

问题


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

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?


回答1:


Use helper_method.

By default, methods in ApplicationController are only accessible inside the Controllers.

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

class ApplicationController < ActionController::Base

  helper_method :foo

  def foo
    "bar"
  end

end

Now the foo method is accessible to both Controllers and Views.




回答2:


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

include ApplicationHelper

to the ApplicationController file?



来源:https://stackoverflow.com/questions/5985761/how-to-call-applicationcontroller-methods-from-applicationhelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!