- Create a new Rails project named School2.
- Generate a Rails scaffold named Student with these fields.
Field | Datatype |
name | string |
gender | string |
phone | string |
- Generate a Rails scaffold named Course with these fields.
Field | Datatype |
course_num | string |
title | string |
credit_hours | integer |
- From the Command Prompt Window, generate a migration to create the join table named courses_students. (Note
that courses and students are in alphabetic order.)
> rails g migration CreateCoursesStudents course_id:integer student_id:integer
Run rake db:migrate to create the table.
- Source code for the School2 seed file
School/db/seeds2.rb.
- Add this line to the Course model file
School2/app/models/course.rb:
has_and_belongs_to_many :students
- Add this line to the Student model file
School2/app/models/student.rb:
has_and_belongs_to_many :courses
- At the bottom of the Course and Student index views, add a link to the index view of the
other model.
- View the show pages with these URLs:
http://localhost:3000/students
http://localhost:3000/courses
- Modify the Student show view to show the courses in which the student is enrolled
(same as School1 Example):
<h3>Courses for <%= @student.name %></h3>
<table>
<tr>
<th>Course Number</th>
<th>Course Title</th>
<th>Credit Hours</th>
</tr>
<% @student.courses.each do |c| %>
<tr>
<td><%= c.course_num %></td>
<td><%= c.title %></td>
<td><%= c.credit_hours %></td>
</tr>
<% end %>
</table>
- Modify the Course show view to show the students that are enrolled in the course
(same as School1 Example):
<h3>Students in <%= @course.course_num %></h3>
<table>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Phone Number</th>
</tr>
<% @course.students.each do |s| %>
<tr>
<td><%= s.name %></td>
<td><%= s.gender %></td>
<td><%= s.phone %></td>
</tr>
<% end %>
</table>
- Add a column to the Course index view to show the number of students in each course
(same as School1 Example):
<td><%= course.students.count %></td>
We now add the capability of enrolling students in new courses.