0

I have two tables with a has_and_belongs_to_many relationship, Project and Category.

I list out all my Project records on my views/projects/new.html.erb like this:

<% @projects.each do |project| %>
  <tr class="project <% project.categories.all.each do |cat| %><%= cat.name %> <% end %>">
     <td><a href='project/<%= project.id %>'><%= project.filename %></a></td>
 <td><%= project.author %>
 <td><% project.categories.all.each do |cat| %><%= cat.name %>, <% end %></td>
  </tr>
<% end %>

And have defined several link_to remote links like this:

<div class="filterBy">SORT BY:</div>
<div class="filterBy"><%= link_to "Category", :update => "projects", :url => { :action => "sortTable", :filter => "Category" }, :remote => true %></div>                                        
<div class="filterBy"><%= link_to "Author", :update => "projects", :url => { :action => "sortTable", :filter => "Author" }, :remote => true %></div>
<div class="filterBy"><%= link_to "Date", :update => "projects", :url => { :action => "sortTable", :filter => "Date" }, :remote => true %></div>

And in my projects_controller I have

def sortTable 
  @projects = Project.find(:all, :order => params[:filter])
end

When I click the links though, nothing happens. What am I doing wrong? I want it to update without refreshing the page as well. If need be, my routes.rb looks like

Docside::Application.routes.draw do
  resources :projects
  resources :categories
  #get "home/index"
  root :to => "projects#new"
  match 'project/new',:controller=>"projects",:action=>"create"
  match "project/:id", :controller => "projects", :action=>"download"
end
4

1 回答 1

0

在您的代码中,您发送远程服务器请求只是为了获取排序数据。这将通过许多请求杀死服务器。由于您的列表页面的主要要求是在不刷新页面的情况下对数据进行排序,因此您可以使用数据表。使用数据表的示例页面 -

添加到你的 appliation.js

//= require jquery.dataTables.min

在用户控制器中

def index
  @users = User.all #collect all the users
end

在您的列表/索引视图中

%table#users
   %thead
     %tr
       %th User Name
       %th User Age
   %tbody
   %tfoot

:javascript 
  var users_list = true;
  var users = #{@users.to_json};  #convert the object collection to json 

在你的 users.js.coffee 文件中

if users_list?
  usersColumnDefs = [ { "bSearchable": true, "bSortable": true, "bVisible": true, "aTargets": [ 0, 1 ] }, { "sClass": "user-name", "aTargets": [ 0 ] }, { "sClass": "user-age", "aTargets": [ 1 ] } ]

  data = $.map(users, (user) ->
    return [[ user.name, user.age ]]
  )

  $('#users').dataTable
    "bSort": false,
    "bPaginate": false,
    "sDom": sDom
    "aaData": data
    "aoColumnDefs": usersColumnDefs

另请参阅 将 jquery DataTables 用于大型数据库的优势是什么?

于 2012-10-08T07:11:33.163 回答