Reputation: 1086
I have a loop that collects all items with index value of 0 via has_many through scenario.
<% @trial.treatment_selections.each do |t| %>
<% t.establishment_methods.each_with_index do |e, index| %>
<% if index == 0 %>
<%= index %> | <%= e.assessment_date %><br />
<% end %>
<% end %>
<% end %>
This out puts 4 dates of the same value all with the same index of 0. ie.
0 | 2018-12-31
0 | 2018-12-31
0 | 2018-12-31
0 | 2018-12-31
My questions is, is there a way to grab only to first item in the loop? e.assessment_date.first
, e.assessment_date[0]
don't seem to be viable options.
Upvotes: 0
Views: 115
Reputation: 1427
You can achieve it in different ways. Following your cycle idea, you could use each_with_index
in your first loop as well:
<% @trial.treatment_selections.each_with_index do |t, outer_index| %>
<% t.establishment_methods.each_with_index do |e, inner_index| %>
<% if outer_index == 0 && inner_index == 0 %>
<%= inner_index %> | <%= e.assessment_date %><br />
<% end %>
<% end %>
<% end %>
But the best way to do it is in just one line
0 | <%= @trial.treatment_selections.first&.establishment_methods.first&.assessment_date %>
The index will always be 0
when you want to print it.
Upvotes: 1