use*_*406 2 ruby ruby-on-rails
我是rails的新手,我收到了这个错误:
undefined method `posts_path' for #<#<Class:0x007fe3547d97d8>:0x007fe3546d58f0>
Run Code Online (Sandbox Code Playgroud)
我在下面发布了我的文件,请记住我是rails的新手,所以简单的解释会非常感激!
Route.rb:
Rails.application.routes.draw do
get '/post' => 'post#index'
get '/post/new' => 'post#new'
post 'post' => 'post#create'
end
Run Code Online (Sandbox Code Playgroud)
post_controller.rb:
class PostController < ApplicationController
def index
@post = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to '/post'
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:content).permit(:title)
end
end
Run Code Online (Sandbox Code Playgroud)
new.html.erb:
<%= form_for(@post) do |f| %>
<div class="field">
<%= f.label :post %><br>
<%= f.text_area :title %>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Create" %>
</div>
<% end %>
Run Code Online (Sandbox Code Playgroud)
我猜想form_for(@post)有一个方法被调用posts_path,一个方法不存在,因为它还没有在你的路由文件中定义.尝试更换:
Rails.application.routes.draw do
get '/post' => 'post#index'
get '/post/new' => 'post#new'
post 'post' => 'post#create'
end
Run Code Online (Sandbox Code Playgroud)
同
Rails.application.routes.draw do
resources :posts, only: [:new, :create, :index]
end
Run Code Online (Sandbox Code Playgroud)
编辑:更多信息:
阅读http://guides.rubyonrails.org/form_helpers.html上的表单助手的完整页面,特别是阅读"2.2将表单绑定到对象"部分以及说:
在处理RESTful资源时,如果依赖于记录标识,对form_for的调用会变得非常容易.简而言之,您可以只传递模型实例并让Rails找出模型名称,其余的:
Run Code Online (Sandbox Code Playgroud)## Creating a new article # long-style: form_for(@article, url: articles_path) # same thing, short-style (record identification gets used): form_for(@article) ## Editing an existing article # long-style: form_for(@article, url: article_path(@article), html: {method: "patch"}) # short-style: form_for(@article)注意短格式form_for调用如何方便地相同,无论记录是新的还是现有的.记录识别是否足够聪明,通过询问record.new_record?来确定记录是否是新记录.它还根据对象的类选择要提交的正确路径和名称.
因此,有意或无意地,当你说form_for(@post),你要求根据@post变量的名称猜测你的表单应该提交的路线.您定义的路线与预期的路线不匹配.
有关在rails中路由的更多信息,请阅读http://guides.rubyonrails.org/routing.html上的整个页面,并特别注意"2资源路由:Rails默认值"部分.您form_for(@post)将假设您正在使用"资源路由",这是我切换到的.
至于为什么你得到一个新的错误?您的应用程序中的其他位置您希望使用以前的自定义路径,现在您正在使用rails"资源路径",因此您的路径名称将不同.没有路线匹配[GET]"/ post/new"因为现在路线改为匹配没有路线匹配[GET]"/ posts/new"(注意复数帖子).
| 归档时间: |
|
| 查看次数: |
3072 次 |
| 最近记录: |