gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:29:44 25 4
gpt4 key购买 nike

开始通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com