简体   繁体   中英

How to sort columns of a table in a Ruby on Rails Application

I'm building a To Do List web application for a school project, and I'm trying to get the headers of the columns to be clickable and when you click them, they sort the information. I've tried so many solutions on here and google tutorials, maybe someone can help me directly?

Here's what I'm trying:
projects_controller.rb

 def index
    @projects = Project.all
    @products = Project.order(params[:sort])

  end

projects.js

$(document).ready(function(){
    $('/index.html.erb').DataTable();
});

index.html.erb

<thead>
      <tr id="headers">
        <th><%= link_to "Title", :sort => "title" %></th>
        <th><%= link_to "Client", :sort => "client" %></th>
        <th>Description</th>
        <th>Hours</th>
        <th><%= link_to "Done", :sort => "done" %></th>
        <th colspan="3"></th>
      </tr>
</thead>

Ok, let me walk you through some debugging since it is for school.

First under your application there is a log folder. The development log gets populated when you run rails s.

Look at what happens when you click the Title link. You want to see a GET with params sort set to title.

That is the physical request that is coming into your server. That is probably perfectly ok by what you have above.

Now, we want to see if the controller, the next step is doing it right.

So an easy way to do that without introducing debuggers is to use raise.

Change your controller to this raise Project.order(params[:sort]).to_sql

This should give you a nice error message that again, confirms you are doing it correctly.

Finally we are going to want to look at the view

You are only sharing the head of the table so I am making the following assumption as to what the rest of the code looks like.

<table id="someid">
    <thead>
        <tr id="headers">
            <th><%= link_to "Title", :sort => "title" %></th>
            <th><%= link_to "Client", :sort => "client" %></th>
            <th>Description</th>
            <th>Hours</th>
            <th><%= link_to "Done", :sort => "done" %></th>
            <th colspan="3"></th>
        </tr>
   </thead>
   <tbody>
        <% @products.each do |product| %>
        ... COLUMNS setout here ....
        <% end %>
   </tbody>
</table>

My gut inclination is that you are rendering @projects and not @products and @products is the one being sorted.

Finally, your jquery appears wrong...

$(document).ready(function(){
    $('/index.html.erb').DataTable();
});

Should probably be

$(document).ready(function(){
    $('#someid').DataTable(); //uses a selector such as the elements id or the class etc 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM