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?
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.