Reputation: 65
I'm creating multiple tables by date and I want my html table rows to be a different colour depending on a number of conditions. With the help of this question I tried out the following in my shift view:
<% (Date.current - 6.months..Date.current + 6.months).each do |date|%>
<% if !Shift.where(date: date).blank? %>
<% @shifts = LaunchShift.where(date: date).all.order(start_time: :asc, booked: :desc) %>
<h2><%= date.strftime('%e %b %Y') %></h2>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>...</th>
</tr>
</thead>
<% @shifts.each_with_index do |shift, index| %>
<% if shift.booked? %>
<% @booker = Member.find(shift.booked_by) %>
<% end %>
<tbody>
<% if shift.booked? %> <---Trying this for changing colour
<tr style="background-color:red">
<% else %>
<tr>
<% end %>
<td><%= shift.start_time.strftime("%H:%M") %></td>
<% if shift.booked? %>
<td>Booked</td>
<td><%= link_to @booker.name, member_path(@booker) %></td>
<% else %>
<td>Free</td>
<td></td>
<% end %>
[...]
</tr>
</tbody>
<% end %>
</table>
</div>
<% end %>
But only some of the rows marked as booked are red, though the shifts.booked? returns as True. Does this approach work differently than I think it does? Is there a better way to do this that that doesn't use JS/JQuery (Don't know those). Any advice? Thank you!
Upvotes: 1
Views: 2545
Reputation: 2927
@ashvin's solution is fine but it would be nice to go one step farther and put the ternary operator into a helper method, thereby keeping your view free of logic. e.g.
<tr class="<%= booked_class(shift) %>">
create a shift_helper.rb file in the helpers folder
module ShiftHelper
def booked_class(shift)
shift.booked? ? "booked" : "available"
end
end
Upvotes: 1
Reputation: 2040
You can try like
.booked{
background-color: red;
}
.available{
background-color: grey;
}
<tr class="<%= shift.booked? ? 'booked' : 'available' %>">
</tr>
If shift is booked then booked class will apply otherwise available class will apply using ternary operator.
Upvotes: 2