Mimo
Mimo

Reputation: 6075

NoMethodError in PostsController#create following the getting started guide

I am a Rails newbie and therefore I am following the getting started guide, available here: http://edgeguides.rubyonrails.org/getting_started.html and here: http://guides.rubyonrails.org/getting_started.html but I can't get the point 5.6 / 5.7 to work.

This is my controller:

class PostsController < ApplicationController
    def new
    end

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

    def create
      @post = Post.new(post_params)

      @post.save
      redirect_to @post
    end

    private
    def post_params
        params.require(:post).permit(:title, :text)
    end

end

and this is my form:

<%= form_for :post, url: posts_path do |f| %>
    <p>
        <%= f.label :title %><br>
        <%= f.text_field :title %>
    </p>

    <p>
        <%= f.label :text %> <br>
        <%= f.text_area :text %>
    </p>

    <p>
        <%= f.submit %>
    </p>
<% end %>

This is the routes.rb

Blog::Application.routes.draw do
  get "welcome/index"

  root 'welcome#index'

  resource :posts

end

but when I submit it, I get this error:

NoMethodError in PostsController#create undefined method post_url' for #<PostsController:0x007f733c415418> with the extract source highlighting the line redirect_to @post. What am I doing wrong? I have ruby 1.9.3 and rails 4.0.0

Upvotes: 2

Views: 1695

Answers (3)

HungryCoder
HungryCoder

Reputation: 7616

In your routes.rb I see you've

resource :posts

I believe, it should be:

resources :posts

Upvotes: 14

tomciopp
tomciopp

Reputation: 2752

Did you add the following line to your config/routes.rb?

resources :posts

Upvotes: 0

amit karsale
amit karsale

Reputation: 755

You might have missed to add the Post part in your routes. Try running rake routes and see what results you get on this :

rake routes | grep post

if you have mentioned post in your routes then may be you are using the wrong path here.

Upvotes: 0

Related Questions