2015-11-17 67 views
-1

我試圖創建對特定教師的評分。我已經添加了學校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 
+2

請檢查您的PARAMS在創建行動閹PARAMS [:學校ID]是來還是不來,並請修改redirect_to的school_teacher_path(PARAMS [:學校ID] params [:teacher_id]) – railslearner

+0

謝謝你的幫助,raje先生。我編輯了該行,但現在出現錯誤:{:action =>「show」,:controller =>「teachers」,:id =>「8」,:school_id => nil}缺少必需的鍵:[: school_id] – NeverGiveUp1989

回答

1

在這一行:

redirect_to school_teacher_path(params[:school_id], [:teacher_id]) 

您傳遞params[:school_id]變量,然後是包含sym的數組bol :teacher_id

我懷疑你真的打算用這樣的:

redirect_to school_teacher_path(params[:school_id], params[:teacher_id]) 
+0

謝謝你的幫助,喬恩先生。但是,現在我得到錯誤: 沒有路線匹配{:action =>「show」,:controller =>「teachers」,:id =>「8」,:school_id => nil}缺少必需的鍵:[:school_id ] – NeverGiveUp1989

+1

那麼你的params變量中沒有'school_id'。在'create'動作的某個地方,您需要找到需要傳遞給路由幫助程序的'school_id',或者您需要修復提交您的創建請求的任何內容,以便將school_id與其餘數據一起發送。 – Jon

+0

我將此行添加到創建操作'@school = School.find(params [:school_id])'中。然後,我得到錯誤:無法找到學校'ID'= – NeverGiveUp1989

相關問題