Reputation: 3
I'm blocked on this since 3 days : Here is my view :
<h1>Liste des livres</h1>
<% @books.each do |book| %>
<p><a href="/books/<%= book.id %>"><%= book.title %></a></p>
<% end %>
<%-# Adding a book %>
<%= form_tag "/books", method: "post" do %>
<input type="text" name="title" />
<input type="submit" value="Ajouter le livre" />
<% end %>
And here is the controller :
class BooksController < ApplicationController
def index
@books = Book.all
end
def create
Book.create title: params[:title]
redirect_to "/books"
end
def show
@book = Book.find(params[:id])
end
def update
Book.find(params[:id]).update title: params[:title]
redirect_to "/books/#{params[:id]}"
end
def destroy
Book.find(params[:id]).destroy
redirect_to "/books"
end
end
Finally my routes :
Rails.application.routes.draw do
get 'pages/home'
get 'books/index'
get 'books' => 'books#index'
post 'books' => 'books#index'
get 'books/:id' => 'books#show'
patch 'books/:id' => 'books#update'
delete 'books/:id' => 'books#destroy'
Now when i insert a book name and click on the button i see this in the terminal :
Started POST "/books" for 127.0.0.1 at 2016-02-17 15:38:39 +0100
Processing by BooksController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"TgLJMVchOq/3yKT2cii82ywS6qNVH8xI9E4mMnuNeI/BK/5SXnRosM0+mKwDlxOEO3WtEg5zttU7Tx69YYJkKQ==", "title"=>"ahah"}
Book Load (0.2ms) SELECT "books".* FROM "books"
Rendered books/index.html.erb within layouts/application (1.3ms)
Completed 200 OK in 27ms (Views: 26.2ms | ActiveRecord: 0.2ms)
But when the pages has refreshed nothing is added and if i open another terminal window and i check in a rails console with Book.all there is nothing more then the original list of books. Is there something wrong with my code ?
Upvotes: 0
Views: 18
Reputation: 659
In your routes your post
request should point to the create
action.
So it should look like this: post 'books' => 'books#create'
not post 'books' => 'books#index'
Upvotes: 1