## 的未定义方法`posts_path’:0x007fe3546d58f0>

我是rails的新手,我收到了这个错误:

undefined method `posts_path' for #<#:0x007fe3546d58f0> 

我在下面发布了我的文件,请记住我是rails的新手,所以简单的解释会非常感激!

Route.rb:

 Rails.application.routes.draw do get '/post' => 'post#index' get '/post/new' => 'post#new' post 'post' => 'post#create' end 

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 

new.html.erb:

  

我猜是form_for(@post)期望有一个名为posts_path的方法,而且一个方法不存在,因为它尚未在您的路由文件中定义。 尝试更换:

 Rails.application.routes.draw do get '/post' => 'post#index' get '/post/new' => 'post#new' post 'post' => 'post#create' end 

 Rails.application.routes.draw do resources :posts, only: [:new, :create, :index] end 

编辑:更多信息:

阅读http://guides.rubyonrails.org/form_helpers.html上的表单助手的完整页面,特别是阅读“2.2将表单绑定到对象”部分以及说:

处理RESTful资源时,如果依赖于记录标识,则可以更轻松地调用form_for。 简而言之,您可以传递模型实例并让Rails找出模型名称,其余的:

 ## 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变量的名称来猜测你应该提交表单的路径。 您定义的路线与预期的路线不匹配。

有关路由路由的更多信息,请阅读http://guides.rubyonrails.org/routing.html上的整个页面,并特别注意“2资源路由:Rails默认值”部分。 您的form_for(@post)将假设您正在使用“资源路由”,这是我切换到的。

至于为什么你得到一个新的错误? 您的应用程序中的其他位置您希望使用以前的自定义路由,现在您正在使用rails“资源路由”,因此您的路径名称将不同。 没有路线匹配[GET]“/ post / new”,因为现在路线改为匹配没有路线匹配[GET]“/ posts / new”(注意复数post)。

这里的表单是尝试通过路径“posts_path”找到到post_method的路由所以你需要在routes.rb文件中定义。

 Rails.application.routes.draw do get '/post' => 'post#index' get '/post/new' => 'post#new' post '/posts' => 'post#create' end