section_name
您在路线中提到了类似的事情。您应该确保所有名称都是 URL 安全的。
您必须考虑的另一点是您想要的两条路径实际上非常相似,因此您可能需要在同一个控制器操作中处理这两条路径。
/view/department_name/course_name/section_name
/view/teacher_name/course_name/section_name
唯一不同的部分是部门名称与教师名称。希望没有和你们系同名的老师XD"
您可以将路径定义为:
get '/view/:department_or_teacher_name/:course_name/:section_name' => 'some_controller#some_action'
然后在你的行动中,你需要这样的东西:
def some_action
department_or_teacher = Department.find_by_name(params[:department_or_teacher_name]) || Teacher.find_by_name(params[:department_or_teacher_name])
course = Course.find_by_name(params[:course_name])
q = Section.where(name: params[:section_name]).where(course_id: course.id)
if department_or_teacher.class.name == "Department"
q = q.where(department_id: q.id)
elsif department_or_teacher.class.name == "Teacher"
q = q.where(teacher_id: q.id)
end
@section = q.first # I assume there should be only 1 section with a given name, under a specific course, and (under a specific department or a specific teacher)
end
上面生成了 3 个查询,这可能不是很好。您可以考虑使用连接:
def some_action
department_or_teacher = Department.find_by_name(params[:department_or_teacher_name]) || Teacher.find_by_name(params[:department_or_teacher_name])
q = Section.where(name: params[:section_name]).joins(:course).where("courses.name = ?", params[:course_name])
if department_or_teacher.class.name == "Department"
q = q.where(department_id: q.id)
elsif department_or_teacher.class.name == "Teacher"
q = q.where(teacher_id: q.id)
end
@section = q.first
end
猜测部门或老师仍然有困难。因此,如果您重新定义这样的路径,上面的内容可能会更清晰:
get '/view/department/:department_name/:course_name/:section_name' => 'some_controller#some_action_for_department'
get '/view/teacher/:teacher_name/:course_name/:section_name' => 'some_controller#some_action_for_teacher'
def some_action_for_department
@section = Section.where(name: params[:section_name])
.joins(:course).where("courses.name = ?", params[:course_name])
.joins(:department).where("departments.name = ?", params[:department_name]) # you mentioned there is a department_id in sections, thus you could actually setup a belongs_to :department in section
.first
end
def some_action_for_teacher
@section = Section.where(name: params[:section_name])
.joins(:course).where("courses.name = ?", params[:course_name])
.joins(:teacher).where("teachers.name = ?", params[:teacher_name])
.first
end
这就是想法。我没有测试它,只是猜测。因此,如果您遇到任何问题,请告诉我。