环境:ruby1.8.7 rails 3.2.7
1.下载jquery-datatables-rails,在gemfile文件中添加 gem "jquery-datatables-rails", "~> 1.10.0"
后执行bundle install
group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', :platforms => :ruby gem 'uglifier', '>= 1.0.3' gem "jquery-datatables-rails", "~> 1.10.0" ##新增 end
2. 分别在application.js 和 application.css文件中添加
application.js //= require dataTables/jquery.dataTables application.css *= require dataTables/jquery.dataTables
3.生成脚手架
rails g scaffold student name:string age:integer sex:string
rake db:migrate
4. 在index.html.erb文件中增加<thean></thead> 和 <tbody></tbody>标签,并给<talbe>加上id属性 值为students
<table id="students" class="display"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Sex</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <% @students.each do |student| %> <tr> <td><%= student.name %></td> <td><%= student.age %></td> <td><%= student.sex %></td> <td><%= link_to 'Show', student %></td> <td><%= link_to 'Edit', edit_student_path(student) %></td> <td><%= link_to 'Destroy', student, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </tbody> </table>
5.在生成的student.js.coffee文件中加入jquery语句,给students元素,即table加上jquery-datatables-rails中 的dataTable()方法,重启服务器,刷新即可
jQuery -> $('#students').dataTable()
6. 附图:
参考资料:http://www.datatables.net/usage/options