I have an employee database with multiple sets of date values. Currently I output this data in this format:

<% @trainings.each do |training| %>
  <tr>
    <td><%= training.birthday %></td>
    <td><%= training.comp_cert %></td>
    <td><%= training.cdl %></td>
    <td><%= training.forklift %></td>
  </tr>
<% end %>

I would like to iterate through these dates on each loop and check the dates against

Time.now + 30.days

but am having some issues. I've tried this:

<% @trainings.each do |training| %>
  <% training.each do |t| %>
    <% if t < Time.now + 30.days %>
      <tr class="warning">
    <% else %>
      <tr class="success">
    <% end %>
  <% end %>

  <!-- Table Data Here -->

<% end %>

but it tells me there is no method called each on training. Is there a more efficient way of doing this rather than just manually checking each of the individual keys?

有帮助吗?

解决方案

You can't iterate on a single object. You can use the iterator pattern only on the collection. I suggest the following approach, for starters :)

<% @trainings.each do |training| %>
  <% %w{birthday comp_cert cdl forklift}.each do |field_name| %>
    <% if training[field_name] < Time.now + 30.days %>
      <tr class="warning">
    <% else %>
      <tr class="success">
    <% end %>
  <% end %>

  <!-- Table Data Here -->

<% end %>

其他提示

You can use helper

def old_training?(training)
  %{birthday comp_cert cdl forklift}.any? { |field| training[field] < Time.now + 30.days }
end

and in view:

<% @trainings.each do |training| %>
    <tr class="<%= old_training?(training) ? "warning" : "success" %>">

    </tr>
<% end %>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top