如果 table 为空 rails,如何在 table 中显示 None

How to display None in a table if the table is empty rails

我有 table 个名字。如果 table 为空,我想在 table 中显示 none。我正在使用 haml、BS4 和 rails 4。到目前为止,我已经试过了:

 - if
   %table.table.table-hover
     - @bill.cosponsors == blank? do
        %tr
           %td= "None"
- else
    %table.table.table-hover
       - @bill.cosponsors.each do |cosponsor|
          %tr
             %td= cosponsor.cosponsor 

我用的是.any?方法。如果@bill.consponsors.any?然后显示它们,显示 "none"

blank? 应该检查属性本身。你可以从 if table 标签中移出一点点 DRY 你的代码:

%table.table.table-hover
   - if @bill.cosponsors.blank?
        %tr
           %td "None"
   - else
     - @bill.cosponsors.each do |cosponsor|
         %tr
           %td= cosponsor.cosponsor 

您应该使用 render @collection 为集合中的每个项目呈现正确的部分,而不是手动迭代集合。

如果集合为空,这将 return nil,允许您在这种情况下有条件地呈现不同的空部分。

如果您的模型名为 'Cosponsor',您应该这样做:

  • app/views/cosponsors/index.html.haml

    %table
      = render(@bill.cosponsors) || render('empty_table')
    
  • app/views/cosponsors/_cosponsor.html.haml

    %tr
      %td= cosponsor.cosponsor
    
  • app/views/cosponsors/_empty_table_partial.html.haml

    %tr.empty
      %td There are no cosponsors
    

请参阅 Rails 指南中的 Rendering Collections