In a Rails index view you iterate the collection and per item in the collection data is presented. In most cases I end up with a complex view, because there is a need to do additional calculations for a specific item in the collection. Here is a typical example:
- if @projects.blank?
= render "shared/placeholder", colspan: "10"
- else
- @hours_total = 0
- @turnover_total = 0
- @projectusers_total = 0
- @projects.each do |project|
- decorate project do |decorates|
- project_calc = ProjectCalculator.new(project)
- hours = project_calc.get_project_data("hours")
- turnover = project_calc.get_project_data("turnover")
- @hours_total += hours
- @turnover_total += turnover
- @projectusers_total += project.projectusers.size
%tr
%td= link_to decorates.data_field(project.name), admin_project_path(project)
%td= decorates.data_field(project.customer.name) unless project.customer.blank?
%td= decorates.data_field(project.company.name_short)
%td= decorates.status
%td= decorates.data_field(project.projectusers.size)
%td= decorates.decimal(hours)
%td= decorates.amount(turnover)
%td= decorates.fixed_price
%td= decorates.show_progress("hours", "compact", hours)
%td= decorates.show_progress("turnover", "compact", turnover)
An improvement I already implemented is to use a decorator for view specific stuff and another one is to use service objects for the actual calculations.
But what bothers me here are all the calculations. What is a solution to make this simpler and ideally not having this in the view?