【问题标题】:Routing Error uninitialized constant路由错误未初始化常量
【发布时间】:2014-01-08 06:03:56
【问题描述】:

我正在尝试学习 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 %>

rake 路线是

  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] "/section/3/edit"

不知道为什么???

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:
    1. 去掉你的 routes.rb 中的第一行和第二行。它们是多余的。 resources 将自动创建这些行。

    2. resources :section 应写为resources :sections。注意它是复数形式。

    3. 在您的index.html.erb 中,您根本不应该提及method:。它是自动设置的,:edit as 方法不存在。方法是指 put 或 get 或 delete,但通常不必提及。

    【讨论】:

      【解决方案2】:

      routes.rb 中不需要此行

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

      将第三行改为:

      resources :sections #plural
      

      如果你删除它们,你可以使用

      点击编辑视图
      <%= link_to "Edit", edit_section_path(section.id), method: :edit %>
      

      这将通过GET 请求在section/3/edit 访问您的应用。

      在您的edit.html.erb 中,您可以使用字段来捕获编辑并执行PUT/section/3

      请注意,RAILS 使用 HTTP 动词来定义 CRUD 操作。参考here

      【讨论】:

        【解决方案3】:

        检查控制器的文件名,因为它应该是复数。它应该与类名匹配。所以,你应该把app/controllers/section_controller.rb重命名为app/controllers/sections_controller.rb

        【讨论】:

          猜你喜欢
          • 2012-05-04
          • 1970-01-01
          • 1970-01-01
          • 2020-11-24
          • 1970-01-01
          • 1970-01-01
          • 2014-02-01
          • 2015-05-23
          • 2018-08-25
          相关资源
          最近更新 更多