GaoVN
GaoVN

Reputation: 33

Getting a "No route matches [PATCH] "/posts.1"" at edit view

I'm following a tutorial for ruby and it's basically finish but when editing it opens up the page for editing but when i click the button to save it it given a No route matches [PATCH] "/posts.1"

My edit view:

<h1>Editing post</h1>

<%= form_for :posts, url: posts_path(@posts), method: :patch do |f| %>

  <% if @posts.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@posts.errors.count, "error") %> prohibited
        this post from being saved:
      </h2>
      <ul>
        <% @posts.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

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

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

<% end %>

<%= link_to 'Back', posts_path %> 

My controller:

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def edit
    @posts = Post.find(params[:id])
  end

  def update
  @posts = Post.find(params[:id])

  if @posts.update(posts_params)
    redirect_to @posts
  else
    render 'edit'
  end
end

  def new
    @posts = Post.new
  end

  def create
      @posts = Post.new(posts_params)
    if @posts.save
        redirect_to @posts
    else
        render 'new'
    end
  end

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

  private
  def posts_params
    params.require(:posts).permit(:title, :description)
  end


end

and i can't seem to find what the problem is, can someone help ?

Upvotes: 0

Views: 1058

Answers (2)

Pardeep Saini
Pardeep Saini

Reputation: 2102

You do not have need to specify the method because rails form_tag call routes based on object @posts if @posts is a new object then it call create action, but in your case @posts exists in your database so it called the update action. Also in your routes you need to specify resources :posts

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

Upvotes: 1

Daniel B
Daniel B

Reputation: 82

You could try changing your form tag to:

<%= form_for(@posts), method: :patch  do |f| %>

Upvotes: 0

Related Questions