Search code examples
ruby-on-railsrubyruby-on-rails-4ruby-on-rails-3.2nested-attributes

No route matches while creating nested resource in Rails


I am trying to create a new teacher for a specific school in my project and I got this error:

No route matches [POST] "/schools/3/teachers/new"

Here is my teachers_controller.rb:

class TeachersController < ApplicationController
  def new
    @teacher = Teacher.new
  end

  def create
    @teacher = Teacher.new(teacher_params)
    @teacher.save

    redirect_to school_path(school)
  end

  private

    def teacher_params
      params.require(:teacher).permit(:firstName, :lastName, :middleName)
    end
end

schools_controller.rb:

class SchoolsController < ApplicationController
  def show
    @school = School.find(params[:id])
  end

  def new
    @school = School.new
  end

  def edit
    @school = School.find(params[:id])
  end

  def update
    @school = School.find(params[:id])

    if @school.update(school_params)
      redirect_to @school
    else
      render 'edit'
    end
  end

  def index
    @schools = School.all
  end

  def create
    @school = School.new(school_params)

    if @school.save
      redirect_to schools_path
    else
      render 'new'
    end
  end

  def destroy
    @school = School.find(params[:id])
    @school.destroy

    redirect_to schools_path
  end

  private

    def school_params
      params.require(:school).permit(:name)
    end
end

routes.rb:

Rails.application.routes.draw do
  resources :schools do
    resources :teachers
  end

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'welcome#index'

And teachers/new.html.erb:

<%= form_for :teacher, url: school_teachers_path(school) do |f| %>
  <p>
    <%= f.label :firstName %><br>
    <%= f.text_field :firstName %>
  </p>

  <p>
    <%= f.label :lastName %><br>
    <%= f.text_field :lastName %>
  </p>

  <p>
    <%= f.label :middleName %><br>
    <%= f.text_field :middleName %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

Solution

  • As your teacher resource is nested under the school resource, so you need to pass the school when you try to create a teacher.

    Try changing your new and create actions in teachers_controller.rb to something like this:

      def new
        @school = School.find(params[:school_id])
        @teacher = @school.teachers.build
      end
    
      def create
        @school = School.find(params[:school_id])
        @teacher = @school.teachers.build(params[:teacher])
        @teacher.save
        redirect_to school_path(@school)
      end
    

    And, then change your form to this:

    <%= form_for([@school, @teacher]) do %>
    . . .
    . . .
    <% end %>