'Make a ASC and Desc link work on my ruby on rails
I added two links that say ASC and Desc but i cant get them to work. I made the links sort by ascending and descending but it isn't doing anything. Any help? (index.html.erb)
<p id="notice"><%= notice %></p>
<% @grades = Grade.all %>
<h1>Grades</h1>
Grade Sort By:
<%= link_to "ASC", grades_path(sort_by: 'asc')%>
<%= link_to "DESC", grades_path(sort_by: 'desc')%>
<table>
<thead>
<tr>
<th><%= link_to "Student", sort: " student_id"%> </th>
<th><%= link_to "Student name", sort: "student_name"%> </th>
<th><%= link_to "Student grade", sort: "student_grade"%> </th>
<th colspan="3"></th>
</tr>
</thead>
(grades_controller.rb)
class GradesController < ApplicationController
before_action :set_grade, only: [:show, :edit, :update, :destroy]
# GET /grades
def index
if !user_signed_in?
redirect_to user_session_path
end
@grades = Grade.all
@grades = @grades.order(student_grade: params[:sort_by]) if params[:sort_by].present?
end
Solution 1:[1]
I believe you should do something like
if params[:sort_by]
@grades = Grade.joins(:student).order( {"students.name": :params[:sort_by]} )
else
@grades = Grade.all
end
and if that does not work go for
if params[:sort_by] == 'asc'
@grades = Grade.joins(:student).order("students.name ASC")
elsif params[:sort_by] == 'desc'
@grades = Grade.joins(:student).order("students.name DESC")
else
@grades = Grade.all
end
Edit: I just noticed the body part of the table is missing. You are not populating the rows of the table by iterating over @grades. Something like
<tbody>
<% @grades.each do |grade| %>
<tr class = "center">
<td><%= grade.student.name %></td>
<td>......</td>
<td>......</td>
</tr>
<% end %>
</tbody>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
