【问题标题】:Change table row colour on condition in Rails在 Rails 中根据条件更改表格行颜色
【发布时间】:2017-03-03 18:34:16
【问题描述】:

我正在按日期创建多个表,并且我希望我的 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 %>

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

【问题讨论】:

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


    【解决方案1】:

    你可以试试

    .booked{
      background-color: red;
    }
    
    .available{
      background-color: grey;
    }
    
    <tr class="<%= shift.booked? ? 'booked' : 'available' %>">
    </tr>
    

    如果预订了班次,则将应用预订的课程,否则将使用三元运算符应用可用的课程。

    【讨论】:

    • 谢谢,这是一个更好的方法。但问题仍然是逻辑在某个地方出错了。并非所有预定的班次都是红色的,也不是所有可用的班次都是灰色的。这可能与创建表的循环中的循环有关吗?数据正确显示,但不知何故 if 语句并不总是有效。有什么想法吗?
    • @SKR 如果数据显示正确,那么如果条件应该正确,想法是如果预定了班次,则将应用红色,否则将应用灰色
    • “不工作”是指可以预订班次,但该行没有着色。表格中的数据是正确的(使用预定?多次并且有效)。奇怪的是 some 行得到正确的颜色,但不是全部。我想这不再是一个css问题而是一个逻辑问题,我应该提出一个新问题。感谢您花时间查看!
    【解决方案2】:

    @ashvin 的解决方案很好,但最好更进一步,将三元运算符放入辅助方法中,从而使您的视图没有逻辑。例如

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

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

    module ShiftHelper
      def booked_class(shift)
        shift.booked? ? "booked" : "available"
      end
    end
    

    【讨论】:

    • 是的,这也是在条件基础上应用类的更好方法。
    猜你喜欢
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2019-12-25
    相关资源
    最近更新 更多