I have 4 models. Departments, Courses, Sections, and Teacher
All of them are heirachically connected with the proper belongs_to and has_many relations. A section belongs to a course which belongs to a department. A teacher has many sections, however, a course has many (is taught by many different) teachers.
I would like to construct the site in such a way that the URL
/view/department_name/course_name/section_name/ shows the section with the name section_name, which belongs to the course named couse_name, which belongs to the department department_name.
However, I also want to /view/teacher_name/course_name/section_name to work the same way, where it shows all the sections associated with that teacher.
How can I do this?
FYI: the different models are connected by their IDs in the database. Section has a course_id integer associated with it, and course has a department_id integer. Section also has a department_id, which is redundant, but that’s how I have it set up.
my routes.rb
Test2::Application.routes.draw do
resources :courses
resources :departments
resources :teachers
resources :sections
resources :courses
You mentioned things like
section_namein your routes. You should make sure the names are all URL-safe.Another point you have to consider is the two paths you want is in fact quite similar and thus you may need to handle both in the same controller action.
The only different part is the department_name vs teacher_name. Hopefully there is no any teacher have the same name with your department XD”
You may define the path as:
Then in your action, you need something like this:
The above generates 3 queries, which might not be very good. You may consider using joins:
There is still a difficulty in guessing the department or teacher. So if you redefine the path to something like this, the above could be cleaner:
This is the idea. I did not test it and just by guess. So please tell me if you encountered any problems.