Wednesday, August 29, 2018

Rails loop in table by column and group

Leave a Comment

I'm looking to produce a looped table that has 3 results for each treatment. I want to one row to contain the date, degrees then list each individual treatment.

Controller

@trial = Trial.find(params[:trial_id]) @max_length = [@trial.treatment_selections].map(&:size).max 

Model

has_many :treatment_selections, primary_key: 'trial_id' has_many :assessments, primary_key: 'trial_id' has_many :methods, through: :assessments 

So far I have this:

<table class="table table-bordered">  <th>Date</th>  <th>Degree</th>  <% @max_length.times do |data| %>  <th><%= @trial.treatment_selections[data].try(:treatment).try(:name) %></th>  <% end %>  <% @max_length.times do |data| %>  <% @trial.methods.order(:treatment_selection_id).order("assessment_date ASC").in_groups_of(3)[data].each_with_index do |e, index| %>   <tr>   <td></td>   <td><%= Time.at(e.try(:assessment).try(:assessment_date)/1000).strftime("%d/%m/%Y") rescue 0 %></td>   <td><%= e.try(:assessment).try(:degrees) rescue 0 %></td>   <td><%= e.try(:total).round(1) rescue 0 %></td>   </tr>    <% end %>   <% end %> </table> 

Which produces this:

enter image description here

But i'd like it to produce this:

enter image description here

2 Answers

Answers 1

I would say there is at least two problems in your code:

1_ Your one liner seems to not work as you think, test the result in console to be sure it's really what you expect. We can't help you more without more details about your models.

<% @trial.methods.order(:treatment_selection_id).order("assessment_date ASC").in_groups_of(3)[data].each_with_index do |e, index| %> 

2_ You can't fill columns 4 (Treatment 2), 5(Treatment 3), 6(Treatment 4) if you only have one <td>...</td> after your <td>...degre...</td>.

You probably need to put a loop here as you did for your <th>treatment x</th>

Answers 2

I guess each row in your last table is an assessment, and each column (treatment 1 to 4) for each assessment is a method. So you would need nested loops:

<% @trial.assessments.order("assessment_date ASC").each do |a| %>   <tr>     <td></td>     <td><%= Time.at(a.try(:assessment_date)/1000).strftime("%d/%m/%Y") rescue 0 %></td>     <td><%= a.try(:degrees) rescue 0 %></td>     <% a.methods.each do |m| %>       <td><%= m.try(:total).round(1) rescue 0 %></td>     <% end %>   </tr>  <% end %> 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment