March 17

0 comments

Shading Cells in Ruby on Rails depending on the contents of the cell

By Christopher Mendla

March 17, 2016


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.

Christopher Mendla

About the author

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}