2014-01-08 40 views
2

我正在嘗試學習RoR。 我的控制器是路由錯誤未初始化的常量

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 

和index.html.erb是

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

耙路線是

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中被

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

我得到的 路由錯誤 未初始化的恆定截面

如果刪除的routes.rb中 則第二線我得到 路由錯誤 無路由匹配[POST] 「/部分/ 3 /編輯」

無法得到原因?

回答

4
  1. 擺脫您的routes.rb中的第一行和第二行。它們是多餘的。 resources將自動創建這些行。

  2. resources :section應該寫爲resources :sections。注意它是複數。

  3. 在你的index.html.erb中,你根本不應該提到method:。它會自動設置,並且:edit作爲方法不存在。方法是指放或取或刪除,但通常不必提及它。

2

你不需要這行你routes.rb

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

更改第三行:

resources :sections #plural 

如果刪除它們,你可以打使用

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

其中wil我的section/3/editGET請求打你的應用程序。

在您的edit.html.erb中,您可以使用字段捕獲編輯並執行PUT/section/3

請注意,RAILS使用HTTP動詞來定義CRUD操作。參考號here

0

檢查你的控制器的文件名,因爲它應該是複數。它應該與類名匹配。所以,您應該將app/controllers/section_controller.rb重命名爲app/controllers/sections_controller.rb

相關問題