Adam
Adam

Reputation: 15

action create couldn't be found for PostsController

I'm following a rails tutorial and need some help to proceed further. Problem is, once I fill out the form which has a title,body fields and hit submit, it has to redirect to the show.html.erb page instead it throws an error.

Error: The action 'create' could not be found for 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>

Any help on this would be appreciated.

Upvotes: 0

Views: 613

Answers (3)

aliibrahim
aliibrahim

Reputation: 1965

Change your routes.rb to this:

Rails.application.routes.draw do

  get "/pages/about" => "pages#about"
  get "/pages/contact" => "pages#contact"

  resources :posts
end

Moreover you should inherit your controller from ActionController::Base

so change first line of your controller to

class PostsController < ActionController::Base

and move the controller to app/controllers/posts_controller.rb

Upvotes: 0

user5245636
user5245636

Reputation:

Note: You are using posts_controller_tests.rb not posts_controller.rb. You are putting your controller code in test controller.

Try to move the code in 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

Upvotes: 1

Tobias
Tobias

Reputation: 4653

Your create action always redirects you to the show action. It doesn't matter if your model was saved or not.

You have to check if the model was saved or not:

 def create
   @post = Post.new(post_params)

   if @post.save
     flash[:success] = 'Successfully saved'
     redirect_to @post
   else
     render 'new'
   end
 end

If it wasn't saved, it renders the new action again.

Upvotes: 0

Related Questions