编辑:如果可能的话,我更愿意使用 Bootstrap 来实现此功能,因为我的项目中有 Bootstrap 。似乎我可能只是缺少在我的 rails 项目中使用 bootstrap 的 javascript 的东西。
单击列名时,表格应按该列名对数据进行排序。下表:
我尝试按照显示的示例使用 Bootstrap 对数据进行排序 at this website ,但它对我不起作用。我错过了什么?
我的 Gemfile 中的相关 gem:
#Gemfile
gem 'bootstrap-sass'
gem 'autoprefixer-rails'
CSS:
#app/assets/stylesheets/application.css.scss
@import "bootstrap-sprockets";
@import "bootstrap";
/*
*= require_tree .
*= require_self
*/
Javascript:
#app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
查看显示记录:
#app/views/index.html.erb
<h4>Listing Users</h4>
<table class=" table table-striped" data-sort-name="name" data-sort-order="desc">
<thead>
<tr>
<th data-field="name" data-sortable="true">Name</th>
<th data-field="age" data-sortable="true">Age</th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.age %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New User', new_user_path %>
最佳答案
感谢Hunter Stevens的大量反馈.我找到的最佳选择是使用 sorttable.js
.我使用的过程如下:
- 添加 gem
'jquery-turbolinks'
给你的Gemfile
修复 turbolink javascript 问题和bundle install
添加
jquery.turbolinks
到 javascript list 文件:#app/assets/javascripts/application.js //= require jquery //= require jquery_ujs //= require jquery.turbolinks //= require bootstrap-sprockets //= require turbolinks //= require_tree .
创建
js
文件位于:app/assets/javascripts/shared/<whatever_you_want_to_call_it>.js
.使用$(document).ready
如图所示修复 Turbo 链接问题。指定一个 IIFE(可选),然后将供应商代码粘贴到该 IIFE 中:$(document).ready(function(){ (function vendorTableSorter(){ /* paste all the vendor code here */ }()); });// end document.ready
然后,只需添加类
sortable
到你的表,这使得所有的列都可以排序:<table class=" table table-striped sortable"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <% @users.each do |user| %> <tr> <td><%= user.name %></td> <td><%= user.age %></td> </tr> <% end %> </tbody>
关于ruby-on-rails - 使用 bootstrap 按 rails 中的列对表数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31483823/