I am a newbie. I just want to create a method in the controller for the following code to avoid repeating again in the view. How can I write in a short and elegant way in ruby on rails?
<% @A = ....... %>
<% @B = ....... %>
<% @C = ....... %>
<% @D = ....... %>
<% @E = ....... %>
<% if (@A || @B || @C) %>
<label> One: </label>
<%= ... %>
<label> Two: </label>
<%= ... %>
<% end %>
<% if (@A || @B || @C || (@D && @E)) %>
<label> Three: </label>
<%= ... %>
<% end %>
assuming your model is called
Userand the code you provided is placed in “app/views/users/show.html.erb”I suggest the following refactoring:
(you need to replace
A,B,C,D and Ewith the appropriate logic and rename the methods to something more meaningful)You can read up on Rails helpers here: http://paulsturgess.co.uk/articles/49-using-helper-methods-in-ruby-on-rails
Basically the reponsibility of a controller is to accept incoming web requests, fetch the neccessary data (
Model) and call the appropriateViewfor rendering.Rails has
Helpersthat can be called from yourViews. The idiom is that you put any advanced logic used in the view into theHelper