让ASC和Desc链接在我的ruby on rails上工作



我添加了两个链接,说ASC和Desc,但我不能让他们工作。我让链接按升序和降序排序,但它没有做任何事情。任何帮助吗?(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

我认为你应该这样做

if params[:sort_by]
@grades = Grade.joins(:student).order( {"students.name": :params[:sort_by]} ) 
else
@grades = Grade.all
end

,如果不行,就用

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

编辑:我刚刚注意到桌子的身体部分不见了。您不是通过遍历@grades来填充表的行。就像

<tbody>
<% @grades.each do |grade| %>
<tr class = "center">
<td><%= grade.student.name %></td>
<td>......</td>
<td>......</td>
</tr>
<% end %>
</tbody>

相关内容

  • 没有找到相关文章

最新更新