如何从 ApplicationHelper 调用 ApplicationController 方法 [英] How to call ApplicationController methods from ApplicationHelper

查看:18
本文介绍了如何从 ApplicationHelper 调用 ApplicationController 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

参考:

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

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

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?

推荐答案

使用helper_method.

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

Use helper_method.

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

ApplicationController 添加一个方法,并使用 helper_method 将其作为辅助方法公开:

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

现在 foo 方法对控制器 视图都可以访问.

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

这篇关于如何从 ApplicationHelper 调用 ApplicationController 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆