3

I'm probably missing some things. Say for example I have a helper function in app/helpers/foo_controller.rb and the code is as follows:

def sample_helper(count)
    #implementaton...
end

and I want to use this helper in a webpage generated by rails and the code is as follows:

    <%= sample_helper(user.id) %>

and if I try to run the webpage it will throw me an error saying that the method is not defined. Thanks in advance!

1
  • it will probably be better for you to look railscasts and himself to find a solution Custom Helper Modules Commented May 27, 2013 at 21:23

2 Answers 2

4

You don't quite have the naming conventions right.

Name your helper file app/helpers/foo_helper.rb and in it you should have this:

module FooHelper
  def sample_helper(count)
    "#{count} items" # or whatever
  end
end

And now, from any view rendered by FooController you should be able to use the sample_helper method.


Also, you should know that if you use the rails generators this structure is setup for you. All you need to do is add methods to the files that get generated. That way you don't need to guess the naming conventions.

For example, this command will make a controller file, controller test files, a helper file, and and an index view file, all ready for you to customize.

rails g controller foo index
Sign up to request clarification or add additional context in comments.

Comments

0

Is your helper should be in a file called app/helpers/foo_helper.rb that contains a a module of the same name as the helper (camelized) Like:

module FooHelper 
  def sample_helper(cont)
    # implementation
  end
end

That's the way Rail auto loads helpers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.