Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ApplicationController methods from 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> 

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?

like image 287
David Avatar asked May 12 '11 23:05

David


People also ask

How do you access the helper method in controller?

In the first version, you can just use html_format - you only need MyHelper. html_format in the second. This does not work when the helper method you want to use make use of view methods such as link_to . Controllers don't have access to these methods and most of my helpers use these methods.

Can we use helper method in controller rails?

It's possible, although not very common, to use helper methods from controller actions. Before Rails 5, you had to include the helper module. In newer versions, you can use helpers in your controller with the helpers (plural) object.


2 Answers

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.

like image 83
Harish Shetty Avatar answered Sep 22 '22 18:09

Harish Shetty


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

 include ApplicationHelper 

to the ApplicationController file?

like image 24
GeorgeW Avatar answered Sep 21 '22 18:09

GeorgeW