2

我是 Rails 新手,使用 jquery 数据库 rails gem 对我的表数据进行排序和搜索。它工作正常,但是当我使用诸如 number_with_delimiter 之类的 rails 辅助方法来显示以逗号分隔的数字时,我没有得到正确的排序结果。

如果不使用 rails helpers,我会得到正确的结果,并且我的表数据排序正确。请问有人可以帮我吗?

这是我的代码:

脚本

    <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $('#d3').dataTable({
        "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "sPaginationType": "bootstrap",
         aaSorting : [[2, 'desc']],  
        });
    });
    </script>

在我的部分表格数据是

    <table class="table table-striped table-bordered "  id="d3">
          <thead>      
           <tr>
             <th>Folder</th>
             <th>#Files</th>
             <th>Source Lines</th>
             <th>Contents</th>
             <th>Description</th>
           </tr>
          </thead>
          <tbody>
           <td>String data</td>
           <td>numeric data</td>
           <td>numeric data</td>
           <td>string data</td>
           <td>string data</td>


          </tbody>
       </table>   

这是我的结果(第三列数据)

SourceLines

 994
 98
 974
 .
 .
 . 
 101
 1,890
 1,674
4

1 回答 1

0

我在使用复数助手将“Hour(s)”添加到一个值时遇到了这个问题。它发生的原因是因为数据表将值视为字符串,而不是数字,并将其排序为一个。

我的解决方案是在我的真实值之前添加一个隐藏的跨度,它可以作为字符串正确排序。隐藏的跨度值是前面有足够多的“0”的数字,以使其与该列中的其他值具有一致的长度。

def datatable_numeric_sort num
    content_tag(:span, number_with_precision(num, :precision => 2).to_s.rjust(10, '0'), :style => "display:none")
end

给定一个 100.5 的数字,它将产生:

<span style="display:none">0000100.50</span>

.to_s.rjust(10, '0') 说“将'0'附加到这个字符串直到它的长度为10”它可以是任何长度,我使用了10,因为我的字符串不应该更长。

就我而言, number_with_precision 是必要的,因为我的数字是小数,并且您需要字符串中小数点的位置一致。

要使用:

<td><%= datatable_numeric_sort record.value%><%= pluralize record.value, "Hour" %></td>
于 2015-11-15T01:35:24.710 回答