– model作成
$ rails g model Post title:string body:text
$ rails db:migrate
### DB接続
$ rails db
sqlite> .tables
ar_internal_metadata posts schema_migrations
// テーブル名は複数形になる
sqlite> select * from posts;
1|title1|body1|2022-01-03 00:47:27.389516|2022-01-03 00:47:27.389516
2|title2|body2|2022-01-03 00:47:34.246581|2022-01-03 00:47:34.246581
sqlite> .quit
db/seeds.rb に初期データを書ける
5.times do |i| Post.create(title: "title #{i}", body: "body #{i}") end
テーブルの中身をリセット
$ rails db:migrate:reset
$ rails db:seed
sqlite> select * from posts;
1|title 0|body 0|2022-01-03 02:38:34.229316|2022-01-03 02:38:34.229316
2|title 1|body 1|2022-01-03 02:38:34.242102|2022-01-03 02:38:34.242102
3|title 2|body 2|2022-01-03 02:38:34.248025|2022-01-03 02:38:34.248025
4|title 3|body 3|2022-01-03 02:38:34.253382|2022-01-03 02:38:34.253382
5|title 4|body 4|2022-01-03 02:38:34.259377|2022-01-03 02:38:34.259377
### controller
$ rails g controller Posts
config/routes.rb
Rails.application.routes.draw do resources :posts end
$ rails routes
Prefix Verb URI Pattern Controller#Action
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
app/controllers/post_controller.rb
class PostsController < ApplicationController def index @posts = Post.all.order(created_at: 'desc') end end
app/views/posts/index.html.erb
<h2>My Posts</h2> <ul> <% @posts.each do |post| %> <li><%= post.title %></li> <% end %> </ul>
$ rails s -b 192.168.33.10 -d
http://192.168.33.10:3000/posts
route pass
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :posts root 'posts#index' end
app/views/layouts/application.html.erb
app/assets/stylesheets/application.css
.container { width: 400px; margin: 20px auto; } body { font-family: Verdana, sans-serif; font-size: 14px; } h2 { font-size: 16px; padding-bottom: 10px; margin-bottom: 15px; border-bottom: 1px solid #ddd; } ul > li { margin-bottom: 5px; }