【问题标题】:I can't save the Post. No route matches [POST] "/posts/new"我无法保存帖子。没有路线匹配 [POST] "/posts/new"
【发布时间】:2017-03-09 18:37:44
【问题描述】:

希望这些文件足以解决问题。一切正常,我只是无法保存帖子。

路线:

Rails.application.routes.draw do
  root 'posts#index'
  resources :posts
end

post_controller:

class PostsController < ApplicationController

  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      flash[:notice] = "Successfully created post!"
      redirect_to post_path(@post)
    else
      flash[:alert] = "Error creating new post!"
      render :new
    end
  end

  private

  def post_params
    params.require(:post).permit(:author, :title, :summary, :body)
  end

end

【问题讨论】:

  • 请从“rake routes”发送输出
  • new 应该用于get 请求而不是帖子(POST 请求)。
  • 前缀动词 URI 模式控制器#Action root GET / posts#index posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new (.:format) 帖子#new edit_post GET /posts/:id/edit(.:format) 帖子#edit post GET /posts/:id(.:format) 帖子#show

标签: ruby-on-rails ruby blogs


【解决方案1】:

确保您的 Post 表单代码如下所示:

<%= form_for(@post) do |f| %>

【讨论】:

  • 把它改成 看看会发生什么。表单助手采用实例变量的名称 - 这里将“@post”作为参数。在此处阅读有关表单助手的更多信息:guides.rubyonrails.org/form_helpers.html
  • ahahashah 我不知道怎么做
【解决方案2】:

您为 post#new 执行“GET”,为 post#create 执行“POST”。 新操作旨在将“POST”所需的表单返回到创建操作。您不会发布到新操作。

【讨论】:

  • 我是 ROR 的新手。我该如何解决?
  • 你的新职位怎么样?您应该有一个如下所示的链接:new_post_path
  • 我在 index.html.erb 中有它
  • 添加你的“rake routes”输出。你重启你的服务器了吗?还将表单发布到您的 new.html 文件中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
相关资源
最近更新 更多