我正在关注rails教程,需要一些帮助才能继续进行。问题是,一旦我填写了具有标题,正文字段和点击提交的表单,它就必须重定向到show.html.erb页面而不是它会引发错误。
错误:找不到PostsController的“创建”操作
routes.rb
Rails.application.routes.draw do
get "/pages/about" => "pages#about"
get "/pages/contact" => "pages#contact"
get "/posts" => "posts#index"
post "/posts" => "posts#create"
get "/posts/show" => "posts#show", as: :show
get "/posts/new" => "posts#new"
end
posts_controller_tests.rb
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
def index
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to show_path
end
def show
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
new.html.erb
<h1>Create a new blog post</h1>
<div class="form">
<%= form_for Post.new do |f| %>
<%= f.label :title %>: <br>
<%= f.text_field :title %> <br> <br>
<%= f.label :body %>: <br>
<%= f.text_area :body %> <br> <br>
<%= f.submit %>
<% end %>
</div>
对此有任何帮助将不胜感激。
答案 0 :(得分:1)
注意:您使用的是posts_controller_tests.rb
而不是posts_controller.rb
。您将控制器代码放在测试控制器中。
尝试移动app/controllers/posts_controller.rb
中的代码:
class PostsController < ApplicationController
def index
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to show_path
end
def show
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
答案 1 :(得分:0)
您的create
操作始终会将您重定向到show动作。您的模型是否已保存无关紧要。
您必须检查模型是否已保存:
def create
@post = Post.new(post_params)
if @post.save
flash[:success] = 'Successfully saved'
redirect_to @post
else
render 'new'
end
end
如果未保存,则会再次呈现新操作。
答案 2 :(得分:0)
将您的routes.rb
更改为:
Rails.application.routes.draw do
get "/pages/about" => "pages#about"
get "/pages/contact" => "pages#contact"
resources :posts
end
此外,您应该从ActionController::Base
将控制器的第一行更改为
class PostsController < ActionController::Base
并将控制器移至app/controllers/posts_controller.rb