作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
在我的 search.html.haml 中,我希望用户能够点击教师姓名,这会将他们带到教师展示页面。但是,它也要求我有 school_id 因为一个老师属于一个学校,而一个学校有很多老师。现在,我想知道是否有办法在不破坏应用程序的情况下将 school_id 添加到路径中。 Rails 现在抛给我的错误是:
No route matches {:action=>"show", :controller=>"teachers", :id=>"1", :school_id=>nil} missing required keys: [: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
最佳答案
school_teacher_path
是用 @school
调用的,它是 nil,因为 find_school
不用于 search
。您可能希望将 @school
替换为 teacher.school
:school_teacher_path(teacher.school, teacher)
。
关于ruby-on-rails - 如何将 school_id 添加到我的路径中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35034530/
我是一名优秀的程序员,十分优秀!