I’m creating a web-app.
While it works great, writing whole pieces of code inside “<% %>” tags in ruby on rails is pretty ugly.
I tried to define a function in my controller.rb and then call it from the html page.
This does not work, as it does not recognize the function.
I’d appreciate any help here. Did I put my function in the correct place? Do I need to load using “require”?
For example:
controller file:
class WelcomeController < ApplicationController
def index
end
def myfunc(x)
puts x
end
end
HTML file (index.html):
<h1>Welcome</h1>
<p>
<%= myfunc(5) %>
</p>
What you are referring to is called a helper in Rails. There are two ways that you could implement this.
Option number one is to place the method you want to access inside a helper module. The most common one is ApplicationHelper which you can find in
RAILS_ROOT/app/helpers/application_helper.rb. If you place the method in there it will be accessible from the views.Another way if you still want/need to have the method in the controller, then you can use the
helper_methodfunction like this:The usage of
privateis not needed, but only good practice so that the method cannot be accidentally used as a Controller action or something.