とほほのRuby on Rails入門

トップ > Ruby on Rails入門 > サンプル1

目次

ファイル

config/routes.rb
Rails.application.routes.draw do
  resources :users
  root 'home#index'
  get 'home/index'
  get '/help', to: 'home#help'
  get '/books', to: 'books#index'
  get '/books/new', to: 'books#new', as: :new_book
  post '/books', to: 'books#create'
  get '/books/:id', to: 'books#show', as: :book
  get 'books/:id/edit', to: 'books#edit', as: :edit_book
  patch '/books/:id', to: 'books#update'
  delete '/books/:id', to: 'books#destroy'
end
app/assets/stylesheets/common.css
h1 { background-color: black; color: white; padding: .8rem; }
a { color: #339; }
input { height: 1.2rem; width: 25rem; margin-bottom: .5rem; }
textarea { height: 3rem; width: 25rem; }
button, input[type=submit] { height: 1.4rem; width: 10rem; margin-bottom: .5rem; }
app/models/book.rb
class Book < ApplicationRecord
end
app/controllers/books_controller.rb
class BooksController < ApplicationController
  def index
    @books = Book.all
  end

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

  def new
    @book = Book.new
  end

  def create
    @book = Book.new(book_params)
    if @book.save
      redirect_to @book
    else
      render :new, status: :unprocessable_entity
    end
  end

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

  def update
    @book = Book.find(params[:id])
    if @book.update(book_params)
      redirect_to @book
    else
      render :new, status: :unprocessable_entity
    end
  end

  def destroy
    @book = Book.find(params[:id])
    @book.destroy
    redirect_to books_path
  end

  private
    def book_params
      params.require(:book).permit(:title, :author)
    end
end
app/views/books/index.html.erb
<h1>Books</h1>
<a href="/">Return</a>
| <%= link_to "Add", new_book_path %>
<ul>
  <% @books.each do |book| %>
    <li><a href="/books/<%= book.id %>"><%= book.title %></a></li>
  <% end %>
</ul>
app/views/books/show.html.erb
<h1>Books</h1>
<a href="/books">Return</a>
<div>Title: <%= @book.title %></div>
<div>Author: <%= @book.author %></div>
<%= button_to "Edit", edit_book_path, method: :get %>
<%= button_to "Delete", @book, method: :delete %>
app/views/books/new.html.erb
<h1>Books</h1>
<a href="/books">Return</a>
<%= form_with model: @book do |form| %>
  <div>
    <div><%= form.label :title %></div>
    <div><%= form.text_field :title %></div>
  </div>
  <div>
    <div><%= form.label :author %></div>
    <div><%= form.text_field :author %></div>
  </div>
  <div>
    <%= form.submit %>
  </div>
<% end %>
app/views/books/edit.html.erb
<h1>Books</h1>
<a href="/books">Return</a>
<%= form_with model: @book do |form| %>
  <div>
    <div><%= form.label :title %></div>
    <div><%= form.text_field :title %></div>
  </div>
  <div>
    <div><%= form.label :author %></div>
    <div><%= form.text_field :author %></div>
  </div>
  <div>
    <%= form.submit %>
  </div>
<% end %>

Copyright (C) 2022 杜甫々
初版:2022年1月9日 最終更新:2022年1月9日
http://www.tohoho-web.com/ex/rails_sample.html