-When I wrote calculations such as the total value and average value of columns in the view, it became confusing and difficult to read. -To solve the problem whether to write in view or controller
First, add it to the gemfile.
gem 'active_decorator'
bundle install.
$ bundle install
Next, create a decorator file. This time it's about a model called score. Please use any name you like for the score part.
$ rails g decorator score
Then it will generate a file like this.
app/decorators/score_decorator.rb
This time it was a golf score, so let me calculate the total of 18H.
module ScoreDecorator
def total_score
format('%+d', hole1_score.to_i +
hole2_score.to_i +
hole3_score.to_i +
・
・
・
hole18_score.to_i)
end
end
Now the view is clean!
<% @scores.each do |score| %>
<%= score.total_score %>
<% end %>
Recommended Posts