Dennis Hackethal
Dennis Hackethal

Reputation: 14275

Update method "No route matches [POST]"

Having a bit of trouble with the following ruby on rails code snippet - I have books and would like to update a book's name, here is how I try to do it:

<h1>Edit the book "<%= @book.name %>"</h1>
<%= form_tag action: :update, id: @book do %>
    <p>
        <label for="book_name">Name</label>
        <%= text_field :book, :name %>
        <%= submit_tag 'Save changes' %>
    </p>
<% end %>

This is what I do in the books controller:

def edit
    @book = Book.find(params[:id])
end

def update
    @book = Book.find(params[:id])
    if @book.update_attributes(params[:book])
        redirect_to :action => 'show', id => @book
    else
        @subjects = Subject.find(:all)
        render :action => 'edit'
    end
end

These are my routes:

root to: 'authors#index'
resources :books, :authors

When I click the submit button in the form, it gives me No route matches [POST] "/books/5" and directs to localhost:3000/books/5 instead of staying and localhost:3000/books/5/edit

What am I doing wrong here? Shouldn't there be a put method for updating stuff somewhere rather than a post method?

Upvotes: 3

Views: 5726

Answers (4)

killebytes
killebytes

Reputation: 980

I had this issue before. Everything was right but still getting the error then I found out it was

gem 'rails-api'

Removed it and it all worked fine.

Upvotes: 0

Ajit Singh
Ajit Singh

Reputation: 146

resources :books should do the job. you dont have to explicitly use "match".

def edit
  @book = Book.find(params[:id])
end

form.html

form_for @book, :method => :put do |f|

def update
@book = Book.find(params[:id])
@book.update_attributes(params[:book])
end

this should do the job.

Upvotes: 2

suresh gopal
suresh gopal

Reputation: 3156

Please try this:

We need to specify match in routes file.

match "/books/:id" => "books#update"

Upvotes: 3

Aaron Renoir
Aaron Renoir

Reputation: 4381

Updates should use put not post.

<%= form_tag( { :controller => :books, :action => :update, :id => @book.id }, { :method => :put } ) do %>

or better yet use form_for

 <%= form_for @book do |f| %>

On your console run "rake routes" and it will print out all available routes.

Upvotes: 4

Related Questions