はじめに
今回作りたい物は付箋アプリです。もう何回目の付箋アプリなのか、分かりませんが、Railsに慣れていくためにも、基本的な事からやっていこうと思います。
環境の準備はこちらを見ながらやってみて下さい。
モデル作成
プロジェクト・データベースは作成済として、モデル作成からまとめていきます。contentカラムはメモ内容を格納する用です。
$ pwd
/home/centos/rails_work/stickeynote
$ rails generate model Note content:string
$ rails db:migrate
後から気付いたのですが、メモに対するタイトルもあれば便利なので、titleカラムも追加します。
$ rails generate migration AddTitleToNotes title:string
$ rails db:migrate
ルーティング設定
想定するページは2つです。必要なページは一覧ページ、編集ページです。
$ cat config/routes.rb
Rails.application.routes.draw do
get 'notes/index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root to: 'notes#index'
resources :notes, :only => [:index, :create, :edit, :update, :destroy]
end
コントローラ作成
ついでにviewも一緒に
$ rails generate controller notes index edit
$ cat app/controllers/notes_controller.rb
class NotesController < ApplicationController
def index
@note = Note.new
@notes = Note.all.page(params[:page]).per(100)
end
def edit
@note = Note.find(params[:id])
end
def update
@note = Note.find(params[:id])
if @note.update(params.require(:note).permit(:title, :content))
redirect_to edit_note_path(@note.id)
else
render edit_note_path(@note.id)
end
end
def create
@note = Note.new(params.require(:note).permit(:title, :content))
if @note.save
redirect_to root_path
end
end
def destroy
@note = Note.find(params[:id])
if @note.destroy
redirect_to root_path
end
end
end
view作成
$ cat app/views/notes/index.html.erb
<h1>トップページ</h1>
<%= form_with(model: @note) do |f| %>
<div>
<%= f.label :title, 'タイトル' %>
<%= f.text_field :title %>
</div>
<div>
<%= f.label :content, 'テキスト' %>
<%= f.text_field :content %>
</div>
<%= f.submit '新規作成' %>
<% end %>
<% @notes.each do |note| %>
<p><%= link_to note.id, edit_note_path(note.id) %> : <%= note.title %> : <%= note.content %> <%= link_to '削除', note_path(note.id), method: :delete %></p>
<% end %>
<%= paginate @notes %>
$ cat app/views/notes/edit.html.erb
<h1>編集</h1>
<%= form_with(model: @note, local: true) do |f| %>
<div>
<%= f.label :title, 'タイトル' %>
<%= f.text_field :title %>
</div>
<div>
<%= f.label :content, 'テキスト' %>
<%= f.text_field :content %>
</div>
<%= f.submit '更新' %>
<% end %>
<%= link_to 'TOP', root_path %>
ページネーションは自作しても良いのですが、試しにkaminariを使って実装してみます。Gemfileにgem 'kaminari'
を追記してbundle install
を実行して下さい。1ページあたり100項目で利用しています。
以上です。rails server -b 0.0.0.0
で起動して使って下さい。
pm2での常駐も
$ pm2 start rails --interpreter bash --name "stickeynote" -- server -b 0.0.0.0