Joe
Joe

Reputation: 1765

Controller calls the helper

I have an easy question: Where to put the helper methods that is called many times by a controller ?
My wish is to keep clear my controller ( user_controller) and I have an helper methods that is called many times (check_permits) is it possible to put this method inside user_helper ?

If yes ==> how to recall it inside user_controller ? If I simply recall check_permits it doesen't recognize it.
If no ==>, where to put the helper methods ?

Upvotes: 1

Views: 692

Answers (2)

Ben Lee
Ben Lee

Reputation: 53319

You are using confusing terminology. In rails, controllers do not have helpers. Helpers are defined as being for the views. It's possible to call helper methods from a controller by using the "helpers" method (see http://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html), but I don't think that's what you're looking for (and generally that's not a good idea anyway).

What you probably want is to either (1) put the method directly in your users_controller.rb as a protected method:

class UsersController < ApplicationController
    ...
    protected
    def check_permits
        ...
    end
end

Or (2) put it in the application_controller.rb if you call it from multiple controllers.

Or (3) put it in a library file as a module and include it in whatever controllers need it. For example, you might create lib/check_permits.rb:

module CheckPermits
    protected
    def check_permits
        ...
    end
end

And then in users_controller.rb:

class UsersController < ApplicationController
    include CheckPermits
    ...
end

Upvotes: 4

Corith Malin
Corith Malin

Reputation: 1525

You can put global helper methods in the application_helper.rb file, but if it's only to be used by one controller each controller can have it's own helper file. Look in app/helper (or app/controller/helper).

Upvotes: 0

Related Questions