0

I'm a newbie in rails and ruby. I'm so confused by some conventions in rails~

I wrote a method like this:

def show_session_counter?
  if session[:counter] && session[:counter] > 4
  end
end

... And want to use the method in application.html.erb like this:

<% if show_session_counter? %>
      <li><a href="#"><%= pluralize session[:counter], "time" %></a></li>
<% end %>

First, I tried to put the method in application.controller.rb because I thought the method will be used in application.html.erb. I tried to put it as a normal method and as a private one. Neither work.

Then I put the method in the application_helper.rb and it works.

So my questions is: why the first way doesn't work? Is there any "rails convention" here?

Thank you so much!

1 Answer 1

1

When you put method inside your controller and want to use it in view, you need to declare it as helper_method.

helper_method :show_session_counter?

def show_session_counter?
  if session[:counter] && session[:counter] > 4
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

Expanding @Mikhail's answer for your second question. The general rails convention here is that if you need it in your controllers, it should go in there with helper_method. If it is only for use in views (HTML generation, custom link settings, etc), then it should be in the helper

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.