Answer the question
In order to leave comments, you need to log in
Why are helpers needed in the context of controllers/views?
What is a helper in a Ruby on Rails application? Why are helpers needed in the context of controllers/views?
Answer the question
In order to leave comments, you need to log in
It is considered bad form to add too much code to a view. If this code is logically related to the controller or model, then there is no problem - place it there. But sometimes there is code purely for presentation. For example, you need to display a list of tags with localization.
Of course, you can place such code in a view
<%- product.tags.each do |tag| %>
<p>
<%= I18n.t(tag, scope: "very.very.very.very.very.very.very.very.long.string.#{product.category}", default: tag.to_s.humanize) %>
</p>
<%- end %>
def localized_tags(product)
product.tags.map do |tag|
I18n.t(tag, scope: "very.very.very.very.very.very.very.very.long.string.#{product.category}", default: tag.to_s.humanize)
end
end
<%- localized_tags(product).each do |tag| %>
<p><%= tag %></p>
<%- end %>
I won’t say exactly why they are needed in controllers, but in views they are needed in order to predefine some function in order to use it in the view.
I think in the controller as well, but for me it's more convenient to just define a new method and use it as a helper.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question