代码之家  ›  专栏  ›  技术社区  ›  DollarChills

使用索引结果获取每个\u中的第一项

  •  0
  • DollarChills  · 技术社区  · 7 年前

    我有一个循环,通过has\u many through场景收集索引值为0的所有项。

    <% @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 %>
    

    这将输出4个具有相同值的日期,所有日期都具有相同的索引0。

    0 | 2018-12-31
    0 | 2018-12-31
    0 | 2018-12-31
    0 | 2018-12-31
    

    我的问题是,有没有办法只抓住循环中的第一个项目? e.assessment_date.first , e.assessment_date[0] 似乎不是可行的选择。

    1 回复  |  直到 7 年前
        1
  •  1
  •   EmmanuelB    7 年前

    你可以用不同的方法来实现它。按照你的循环理念,你可以 each_with_index 在第一个循环中:

    <% @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 %>
    

    但最好的办法就是一句话

    0 | <%= @trial.treatment_selections.first&.establishment_methods.first&.assessment_date %>
    

    0 当你想打印的时候。