在Rails中更改表格行颜色

时间:2017-03-03 10:09:46

标签: css ruby-on-rails html-table

我按日期创建多个表格,我希望我的html表格行可以根据许多条件使用不同的颜色。在this question的帮助下,我在班次视图中尝试了以下内容:

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

但是只有部分标记为已预订的行是红色的,但是shift.booked?返回True。这种方法的工作方式与我认为的方式不同吗?有没有更好的方法来做到这一点,没有使用JS / JQuery(不知道那些)。有什么建议? 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试

.booked{
  background-color: red;
}

.available{
  background-color: grey;
}

<tr class="<%= shift.booked? ? 'booked' : 'available' %>">
</tr>

如果预订班次,则预订班级将适用,否则将使用三元运营商申请。

答案 1 :(得分:1)

@ ashvin的解决方案很好但是再向前走一步并将三元运算符放入辅助方法会更好,从而保持视图不受逻辑影响。例如

<tr class="<%= booked_class(shift) %>">

在helpers文件夹中创建shift_helper.rb文件

module ShiftHelper
  def booked_class(shift)
    shift.booked? ? "booked" : "available"
  end
end
相关问题