Created
September 3, 2014 20:39
-
-
Save gilbert/cb785b541d0f2258aae7 to your computer and use it in GitHub Desktop.
Rails forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Book < ActiveRecord::Base | |
validates :name, :presence => true | |
validates :published_at, :presence => true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BooksController < ApplicationController | |
def index | |
@books = Book.all | |
@book = Book.new | |
end | |
def show | |
@book = Book.find params[:id] | |
end | |
def create | |
book = Book.new(book_params) | |
if book.save | |
# Redirect to the new book's show page | |
redirect_to "/books/#{book.id}" | |
else | |
@book = book | |
@books = Book.all | |
render 'index' | |
end | |
end | |
def edit | |
@book = Book.find params[:id] | |
end | |
def book_params | |
params.require(:book).permit(:name, :published_at) | |
end | |
def update | |
end | |
def destroy | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>New Book</h2> | |
<% if @book.errors.any? %> | |
<p><%= @book.errors.messages.inspect %></p> | |
<% end %> | |
<%= form_tag("/books", method: "post") do %> | |
<%= label_tag('book[name]', "Title:") %> | |
<%= text_field_tag('book[name]', @book.name) %><br> | |
<%= label_tag('book[published_at]', "Published:") %> | |
<%= date_field_tag('book[published_at]', @book.published_at) %><br> | |
<%= submit_tag("submit") %> | |
<% end %> | |
<h2>All Books:</h2> | |
<% @books.each do |book| %> | |
<p> | |
<%= link_to book.name, "/books/#{book.id}" %> | |
</p> | |
<% end %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails.application.routes.draw do | |
get '/' => 'books#index' | |
get 'books/:id' => 'books#show' | |
post '/books' => 'books#create' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1><%= @book.name %></h1> | |
<p>Published at: <%= @book.published_at %></p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment