As we have already seen, it's common to have items in one model belong to an item in another table. The reference uses a foreign key (see pp. 200-205). For example, reviews in the Review model belong to a student in the Student model.
It's easy to create scaffolds and routes for both models, but what if you want to route a request from one model to the other? For example, what if you want to create a new review when viewing a particular student?
Adding the following statement in the config/routes.rb file provides routes from Student views to the Review controller:
map.resources :students, :has_many => :reviews
The command rake routes will then allow you to see the resulting paths that are created (also see pp. 217 - 220).
The following link can then be added to show.html.erb in views/student:
<%= link_to 'Create Review for Student', new_student_review_path(@student) %>
Assuming a student id of 2, this link will have the following URL:
http://localhost:3000/students/2/reviews/new
The new route will then call the new method in the Reviews controller.
It would be nice if the new review form had the correct student automatically selected. To do that, we need to modify the Review.new method call to insert the correct student id:
@review = Review.new(:student_id => params[:student_id])
If there is no student_id parameter, nil is simply assigned to student_id.