Skip to content

Instantly share code, notes, and snippets.

@gilbert
Created September 3, 2014 20:39
Show Gist options
  • Save gilbert/cb785b541d0f2258aae7 to your computer and use it in GitHub Desktop.
Save gilbert/cb785b541d0f2258aae7 to your computer and use it in GitHub Desktop.
Rails forms
class Book < ActiveRecord::Base
validates :name, :presence => true
validates :published_at, :presence => true
end
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
<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 %>
Rails.application.routes.draw do
get '/' => 'books#index'
get 'books/:id' => 'books#show'
post '/books' => 'books#create'
end
<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