Where to use Ruby methods for Rails controllers?

I have some Ruby methods that need certain (or all) controllers. I tried putting them in /app/helpers/application_helper.rb . I used this for the methods that will be used in the views. But controllers do not see these methods. Is there another place I should put them, or do I need to access these helper methods in different ways?

Using the latest stable Rails.

+51
ruby ruby-on-rails ruby-on-rails-3 view-helpers
Nov 28 '12 at 19:48
source share
5 answers

You must define a method inside the ApplicationController .

+61
Nov 28
source share
β€” -

For Rails 4, problems are the way to go. There is a decent article here http://richonrails.com/articles/rails-4-code-concerns-in-active-record-models

In essence, if you look in your folder with controllers, you will see a folder with problems. Create a module there in these lines

 module EventsHelper def do_something end end 

Then in the controller just turn it on

 class BadgeController < ApplicationController include EventsHelper ... end 
+40
Oct 09 '14 at 13:03 on
source share

you must define the methods inside the application controller, if you have several methods, then you can follow these steps

 class ApplicationController < ActionController::Base helper_method :first_method helper_method :second_method def first_method ... #your code end def second_method ... #your code end end 

You can also include auxiliary files as shown below.

 class YourController < ApplicationController include OneHelper include TwoHelper end 
+25
Nov 28
source share

You can call any helper methods from the controller using view_context , for example

 view_context.my_helper_method 
+14
Nov 28 '12 at 20:00
source share

Ryan Bigg's answer is good.

Another possible solution is to add helpers to your controller:

 class YourController < ApplicationController include OneHelper include TwoHelper end 

Regards!

+7
Nov 28 '12 at 19:59
source share



All Articles