按班级排序学生

时间:2014-08-26 15:28:39

标签: ruby-on-rails

我的学生模型包含 name:string classroom:string 列。

我希望有一个页面列出每个班级的学生。

即。
本地主机:3000 /学生/ 1E1
     本地主机:3000 /学生/ 1E2
     localhost:3000 /学生/ 1E3

我似乎无法解决问题。这是我尝试独立工作的第一个Rails应用程序。但我真的被困住了!希望有人可以帮助我。

此代码位于我的students_controller.rb

class StudentsController < ApplicationController
  def index
    @students = Student.all
  end

  def show
    @student = Student.find(params[:id])
  end


  def sort_by_class
    @student = Student.find(params[:id])
    @class = @student.classroom
  end

end

此代码位于我的show.html.erb

<h1>Students#show</h1>
<p>Find me in app/views/students/show.html.erb</p>


<%= @student.name %>
<%= @student.classroom%>

3 个答案:

答案 0 :(得分:2)

最好是将“教室”作为模型并与学生联系:

m-n学生和课堂协会:The has_and_belongs_to_many Association

在终端生成:

rails g model classroom number:string
rails g migration create_classrooms_student classroom:references student:references

<强>模型/ student.rb

class Student < ActiveRecord::Base

  has_and_belongs_to_many :classrooms

end

<强>模型/ classroom.rb

class Classroom < ActiveRecord::Base

  has_and_belongs_to_many :students

end

OR 1-n学生和课堂协会:

在终端生成:

rails g model classroom number:string
rails g migration add_classroom_id_to_students classroom:references

<强>模型/ student.rb

class Student < ActiveRecord::Base

  belongs_to :classroom

end

<强>模型/ classroom.rb

class Classroom < ActiveRecord::Base

  has_many :students

end
两个示例的

控制器

<强>控制器/ classrooms_controller.rb

class ClassroomsController < ApplicationController
  def index
    @classrooms = Classroom.all
  end

  def show
    @classroom = Classroom.find(params[:id])
  end
end

<强> show.html.erb

<h1><%= @classroom.number %></h1>

<table>
  <thead>
  <tr>
    <th> Name </th>
  </tr>
  </thead>
  <tbody>
    <% @classroom.students.each do |student| %>
      <tr>
        <td><%= student.name %></td>
      </tr>
    <% end %>
  </tbody>
</table>

您的网址:

localhost:3000/classrooms/1E1

答案 1 :(得分:0)

sort_by_class是另一条路线还是你想在索引中按类排序?

假设教室是与学生(belongs_to:教室)的关联,并且您在Student表中有一个classroom_id列,您可以执行类似Student.order(:classroom_id)的操作

答案 2 :(得分:0)

或简单的方式:

为课堂创建新的控制器

class ClassroomsController < ApplicationController
  def index
    @classrooms = Student.group(:classroom).pluck(:classroom)
  end

  def show
    @classroom = params[:id]
    @students = Student.where(params[:id])
  end
end

<强> index.html.erb

<h1>Classrooms</h1>
<table>
  <% @classrooms.each do |classroom| %>
    <tr>
      <td><%= classroom %></td>
      <td><%= link_to(classroom, classroom_path(classroom)) %></td>
    </tr>
  <% end %>
</table>

<强> show.html.erb

<h1>Classroom <%= @classroom %> Students</h1>
<table>
  <% @students.each do |student| %>
    <tr>
      <td><%= student.name %></td>
    </tr>
  <% end %>
</table>