Ammar Hayder Khan
Ammar Hayder Khan

Reputation: 1335

Routing Error uninitialized constant

I am trying to learn RoR. MY controller is

class SectionController < ApplicationController
  def new
    if request.post?
      u=SectionMst.new( :section_name => params[:section_name])
      u.save
      redirect_to("/section")
    else
      render 
    end
  end

  def index
    @sections = SectionMst.all
  end

  def destroy
    u=SectionMst.destroy(params[:id])
    u.save
    redirect_to("/section")
  end

  def edit
    @user = SectionMst.find(params[:id])
  end
end

and index.html.erb is

<%= link_to "Edit", edit_section_path(section.id), method: :edit %>

rake routes is

  section_new  POST   /section/new(.:format)      section#new
               POST   /section/:id/edit(.:format) section/:id#edit
 section_index GET    /section(.:format)          section#index
               POST   /section(.:format)          section#create
 new_section   GET    /section/new(.:format)      section#new
 edit_section  GET    /section/:id/edit(.:format) section#edit
      section  GET    /section/:id(.:format)      section#show
               PUT    /section/:id(.:format)      section#update
               DELETE /section/:id(.:format)      section#destroy

routes.rb is

post "section/new"
post "section/:id/edit"
resources :section

i am getting the Routing Error uninitialized constant Section

if i delete the second line of routes.rb then i get Routing Error No route matches [POST] "/section/3/edit"

not able to get why???

Upvotes: 2

Views: 7520

Answers (3)

Aboozar Rajabi
Aboozar Rajabi

Reputation: 1793

Check your controller's file name because it should be plural. It is supposed to match the class name. So, you should rename app/controllers/section_controller.rb to app/controllers/sections_controller.rb.

Upvotes: 0

Danny
Danny

Reputation: 6025

  1. Get rid of the first and second lines in your routes.rb. They're redundant. The resources will create these lines automatically.

  2. The resources :section should be written as resources :sections. Notice that it's plural.

  3. In your index.html.erb, you shouldn't mention method: at all. It's automatically set, and :edit as method doesn't exist. Method refers to put or get or delete, but you normally don't have to mention it.

Upvotes: 4

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

You do not need this lines in your routes.rb

post "section/new"
post "section/:id/edit"

Change the third line to:

resources :sections #plural

If you delete them, you can hit the edit view using

<%= link_to "Edit", edit_section_path(section.id), method: :edit %>

which will hit your app at section/3/edit with a GET request.

In your edit.html.erb, you can then have fields to capture edits and do a PUT to /section/3.

Note that RAILS uses HTTP verbs to define the CRUD operations. Ref here.

Upvotes: 2

Related Questions