Last Updated on September 16, 2020 by Christopher G Mendla
I wanted to change the background color of a cell in Ruby on Rails depending on if the contents of and expires field was past or not. Â This could be useful for dashboard type apps or pages. i.e. red/yellow/green
index.html.erb
<% @user_messages.each do |user_message| %>
 <tr>
<td>
<%= user_message.message.html_safe %>
</td>
<% get_expires(user_message.expires)Â %> Â
 <td style="background-color: <%=$expires_color%>">
<%= $expires_formatted.strftime("%m/%d/%y") %>
<br>
<%= $expires_formatted.strftime("%I:%M %p") %>
</td>
<td>
<%= link_to 'Show', user_message %>
</td>
<td>
<%= link_to 'Edit', edit_user_message_path(user_message) %>
</td>
<td>
<%= link_to 'Destroy', user_message, method: :delete, data: { confirm: 'Are you sure?' } %>
</td>
</tr>
<% end %>Â Â
<td>
<%= user_message.message.html_safe %>
</td>Â Â
<% get_expires(user_message.expires)Â %>
<td style="background-color: <%=$expires_color%>">
<%= $expires_formatted.strftime("%m/%d/%y") %>
<br>
<%= $expires_formatted.strftime("%I:%M %p") %>
</td>
<td>
<%= link_to 'Show', user_message %>
</td>
<td>
<%= link_to 'Edit', edit_user_message_path(user_message) %>
</td>Â Â
<td>
<%= link_to 'Destroy', user_message, method: :delete, data: { confirm: 'Are you sure?' } %>
</td>Â
</tr>
<% end %>
The method in the controller is
helper_method :get_expires
def get_expires(expires)
# this grabs the expires date, then sets a variable for the
# strftime function in user_messagesindex Â
# If the expires date/time is past, a variable is set
# which is used in the TD style statement for that cell Â
$expires_color = 'lightgreen'
$expires_formatted = expires
if $expires_formatted.past?
$expires_color = '#ffcccc'
end
end
The key to making this work is to pass the date you want to the method with
<% get_expires(user_message.expires) %>
Then the method sets the appropriate value for the shading. which is used in the style statement for the TD
<td style="background-color: <%=$expires_color%>">
 If the background color is too much, you can simply change the style to change the text color instead.