我試圖創建對特定教師的評分。我已經添加了學校ID到我的評級表中,但仍然得到錯誤:沒有路線匹配{:action =>「show」,:controller =>「teachers」,:id =>「teacher_id」,:school_id => nil}缺少必需的鍵:[:school_id]
No route matches {:action=>"show", :controller=>"teachers", :id=>"teacher_id", :school_id=>nil} missing required keys: [:school_id]
redirect_to school_teacher_path(params[:school_id], [:teacher_id])
這裏是我的路由文件的routes.rb:
Rails.application.routes.draw do
resources :schools do
resources :teachers
end
resources :teachers do
resources :ratings
end
ratings_controller.rb:
class RatingsController < ApplicationController
def new
get_teacher
@rating = @teacher.ratings.build
end
def create
get_teacher
@rating = @teacher.ratings.build(rating_params)
if @rating.save
redirect_to school_teacher_path(params[:school_id], [:teacher_id])
else
render 'new'
end
end
def get_teacher
@teacher = Teacher.find(params[:teacher_id])
end
private
def rating_params
params.require(:rating).permit(:easiness, :helpful, :clarity, :comment,
:teacher_id, :school_id)
end
end
ratings/new.html.erb:
<h1>Teacher Rating</h1> <%= form_for([@teacher, @rating]) do |f| %> <p>
<%= f.label :clarity %>
<%= f.text_field :clarity %> </p>
<p>
<%= f.label :easiness %>
<%= f.text_field :easiness %> </p>
<p>
<%= f.label :helpfulness %>
<%= f.text_field :helpfulness %> </p>
<p>
<%= f.label :comment %>
<br>
<%= f.text_area :comment %> </p>
<p>
<%= f.submit %> </p> <% end %>
rating.rb:
class Rating < ActiveRecord::Base
belongs_to :teacher, dependent: :destroy
end
teacher.rb:
class Teacher < ActiveRecord::Base
belongs_to :school
has_many :ratings
def name
"#{firstName} #{middleName} #{lastName}"
end
def to_s
name
end
end
school.rb:
class School < ActiveRecord::Base
has_many :teachers, dependent: :destroy
validates :name, presence: true,
length: { minimum: 5 }
end
請檢查您的PARAMS在創建行動閹PARAMS [:學校ID]是來還是不來,並請修改redirect_to的school_teacher_path(PARAMS [:學校ID] params [:teacher_id]) – railslearner
謝謝你的幫助,raje先生。我編輯了該行,但現在出現錯誤:{:action =>「show」,:controller =>「teachers」,:id =>「8」,:school_id => nil}缺少必需的鍵:[: school_id] – NeverGiveUp1989