ruby-on-rails - rails 4 : use of form_for , 没有路线,POST

标签 ruby-on-rails routes

开始通过 Lynda 学习 Ruby on Rails - 非常兴奋,我正在尽最大努力尽可能多地练习。我正在学习这些练习,但培训是基于 Rails 3 的 - 到目前为止,一些用途尚未被接受。

情况是这样的:

我在 subjects/new 到达创建表单 填写表格 返回如下错误

No route matches [POST] "/subjects/create"

Rails.root: /Users/alpozenalp/Sites/simple_cms

我花了最后 2 个小时在 stackoverflow、rail guide 和所有其他资源之间闲逛——尝试了很多变体,但无法通过这个阶段。

非常感谢您的帮助。

路线.rb

SimpleCms::Application.routes.draw do

root :to => "demo#index"
get ':controller(/:action(/:id(.:format)))'

end

subjects_controller.rb

class SubjectsController < ApplicationController

def index
list
render('list')
end

def list
@subjects = Subject.order("subjects.position ASC")
end

def show
@subject = Subject.find(params[:id])
end

def new
@subject = Subject.new
end

def create
# Instantiate a new object using form parameters
@subject = Subject.new(params[:subject])
# Save the object
if @subject.save
# If save succeeds, redirect to the list action
redirect_to(:action => 'list')
else
# If save fails, redisplay the form so user can fix problems
render('new')
end
end
end

new.html.erb

<%= link_to("<< Back to List", {:action => 'list'}, :class => 'back-link') %>

<div class="subject new">
  <h2>Create Subject</h2>

  <%= form_for(:subject, :url => {:action => 'create'}, :method => :post) do |f| %>

    <table summary="Subject form fields">
      <tr>
        <th>Name</th>
        <td><%= f.text_field(:name) %></td>
      </tr>
      <tr>
        <th>Position</th>
        <td><%= f.text_field(:position) %></td>
      </tr>
      <tr>
        <th>Visible</th>
        <td><%= f.text_field(:visible) %></td>
      </tr>
    </table>

    <div class="form-buttons">
      <%= submit_tag("Create Subject") %>
    </div>

  <% end %>
</div>

最佳答案

naomik 的回答肯定会帮助表单更清晰,但听起来您只需要在 config/routes.rb 文件中为主题添加一条路线:

SimpleCms::Application.routes.draw do

  resources :subjects    
  root :to => "demo#index"

end

更多信息在 Rails routing guide .

编辑:根据 naomik 的建议删除了默认的回退路由。

关于ruby-on-rails - rails 4 : use of form_for , 没有路线,POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18472107/

相关文章:

javascript - 如何在身份验证后从静态 Express 页面提供整个 angularJS SPA?

node.js - Mongoose 模型中的元排序

ruby-on-rails - 在 Controller 中渲染 JSON

ruby-on-rails - 如何停止 Rails 中的守护进程服务器?

ruby-on-rails - 有没有一种简单的方法可以在运行迁移之前对其进行测试?

ruby-on-rails - 访问仪表板时,rails_admin 一直给我未定义的局部变量或方法 `rails_admin'

c# - ASP.Net MVC 3 路由损坏

Laravel Route() 参数 UTF-8 问题

javascript - 如何在表单提交时向路由发送参数

css - 使用 btn-block 使 Bootstrap-Select 按钮全宽(响应)