| Field | Datatype |
|---|---|
| name | string |
| gender | string |
| phone | string |
| Field | Datatype |
|---|---|
| course_num | string |
| title | string |
| credit_hours | integer |
| Field | Datatype |
|---|---|
| student_id | integer |
| course_id | integer |
# In the School3/app/models/enrollment.rb belongs_to :course belongs_to :student # In School3/app/models/course.rb has_many :enrollments has_many :students, through: :enrollments # In School3/app/models/student.rb has_many :enrollments has_many :courses, through: :enrollments
http://localhost:3000/students http://localhost:3000/courses
<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>
<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>
<td><%= course.students.count %></td>
We now add the capability of enrolling students in new courses.
# Check if student is enrolled in a course def enrolled_in?(course) return self.courses.include?(course) end # Get list of all courses that a # student is not enrolled def unenrolled_courses return Course.all - self.courses end
def add_course
@student = Student.find(params[:id])
@course = Course.find(params[:course])
if not @student.enrolled_in?(@course)
enroll = Enrollment.new
enroll.student_id = @student.id
enroll.course_id = @course.id
enroll.save
end
redirect_to @student
end
Add this form to the bottom of the Student show method
before the Edit and Back links.
<% if @student.enrollments.count < Course.count %>
<p>Enroll in a course.</p>
<%= form_tag add_course_student_path(@student) do %>
<%= select_tag(:course,
options_from_collection_for_select(
@student.unenrolled_courses, :id, :course_num)) %>
<%= submit_tag 'Enroll' %>
<% end %>
<% end %>
resources :students do
member do
post :add_course
end
end