在我的search.html.haml中,我希望用户能够点击教师名称,然后将其引导到教师节目页面。然而,它还要求我拥有school_id,因为老师属于学校,学校有很多老师。现在,我想知道我是否有办法让school_id到路径而不破坏应用程序。 rails现在向我投掷的错误是:
没有路线匹配{:action =>“show”,:controller =>“teachers”,:id =>“1”, :school_id => nil}缺少必需的键:[:school_id]
以下是我的文件:
search.html.haml :
.text-center
/ No search results announcement/notification
- if @teachers.blank?
%h2 Xin lỗi, hệ thống chúng tôi không có thông tin về giảng viên mà bạn muốn tìm.
- else
- @teachers.each do |teacher|
%h2= link_to teacher.fullName, school_teacher_path(@school, teacher)
#note
%em
Khoa #{teacher.department}, trường #{teacher.school.name}
teachers_controller.rb :
class TeachersController < ApplicationController
before_action :find_school, except: [:welcome, :search]
before_action :find_teacher, only: [:show, :edit, :update, :destroy]
def welcome
end
def show
end
def search
if params[:search].present?
@teachers = Teacher.search(params[:search], fields: [:fullName])
else
@teachers = nil
end
end
def new
@teacher = @school.teachers.build
end
def create
@teacher = @school.teachers.create(teacher_params)
@teacher.save
redirect_to(@school)
end
def edit
end
def update
@teacher.update(teacher_params)
redirect_to(@school)
end
private
def find_school
@school = School.find(params[:school_id])
end
def find_teacher
@teacher = Teacher.find(params[:id])
end
def teacher_params
params.require(:teacher).permit(:firstName, :lastName, :middleName, :department, :school_id, :fullName)
end
end
teacher.rb :
class Teacher < ActiveRecord::Base
belongs_to :school
has_many :ratings
searchkick
def name
"#{lastName} #{middleName} #{firstName}"
end
def to_s
name
end
end
school.rb :
class School < ActiveRecord::Base
has_many :teachers, dependent: :destroy
# searchkick
end
的routes.rb :
Rails.application.routes.draw do
devise_for :users
resources :schools do
# collection do
# get 'search'
# end
resources :teachers do
collection do
get 'search'
end
end
end
resources :teachers do
collection do
get 'search'
end
resources :ratings
end
root 'teachers#welcome'
end
答案 0 :(得分:4)
school_teacher_path
的调用@school
为{0},因为find_school
未用于search
。您可能希望将@school
替换为teacher.school
:school_teacher_path(teacher.school, teacher)
。