コラム: エラーメッセージを日本語にする
STEP①Githubのrails-i18nの日本語辞書リポジトリをDL
$ wget https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml -P config/locales
wget は引数に記載したURLからファイルをカレントディレクトリにDLするコマンド。(Command not foundと出た場合の対処法)
-P オプションでDLするディレクトリを指定します。
これで、翻訳ファイルconfig/locales/ja.yml が作成される。
STEP②config/initializers/locale.rbファイルを作成
vim config/initializers/locale.rb
STEP③以下を記述して保存(:wq コマンドで保存できる)
config/initializers/locale.rb
Rails.application.config.i18n.default_locale = :ja
モデルの雛形作り
$rails g model モデル名 属性名:データ型 name:string description:text
モデルが動作するには、データベースとモデルクラスの両方が必須。
データベースにテーブルを追加する為に、マイグレーションを実行する。
※Railsで用意されているマイグレーションという仕組みは、スキーマの歴史を進めるだけでなく、戻す機能も備えている。
$rails db:migrate
コントローラの雛形作り
$rails g controller tasks index show new edit
config.routes.rbから余計なものを削除し、resourcesにまとめる
config.routes.rb
root to: 'tasks#index'
resources :tasks
一覧画面(index)から新規登録ボタンを作ってリンクを飛ばす
app/views/〜/index.html.slim
= link_to '新規登録', new_task_path, class: 'btn btn-primary'
翻訳処理
config/locales/ja.yml
error:
〜
〜
model:
task: タスク
attributes:
id: ID
name: 名称
description: 詳しい説明
created_at: 登録日時
updated_at: 更新日時
ここら辺を任意で記載。
新規登録画面の為のアクションを実装
app/controllers/tasks_controller.rb
def new
@task = Task.new
end
※アクションからビューに受け渡しをしたいデータをインスタンス変数に入れるのが、アクションの基本役割の一つ。
新規登録画面のビューを作成
app/views/tasks/new.html.slim
form_withを使ってぽちぽち
登録アクションの実装
app/controllers/tasks_controller.rb
def create
task = Task.new(task_params)
task.save!
redirect_to tasks_url, notice: "タスク 「#{task.name}」を登録しました」"
end
private
def task_params
params.require(:task).permit(:name, :description)
end
end
※なぜrenderでなく、redirect_toなのかは➡︎RenderとRedirectの違い
このままだとnoticeが表示されないので、application.htmlを直す
application.html.slim
.container
- if flash.notice.present?
.alert.alert-success = flash.notice
一覧表示機能の実装
コントローラ
tasks_controller.rb
def index
@tasks = Task.all
end
ビューの処理
index.html.slim
=link_to '新規登録'〜
.mb-3
table.table.table-hover
thread.thread-default
tr
th= Task.human_attribute_name(:name)
th= Task.human_attribute_name(:created_at)
tbody
- @tasks.each do |task|
tr
td= task.name
td= task.created_at
詳細表示機能の実装
さっき書いた一覧にリンクをつける
index.html.slim
td = link_to task.name, task_path(task)
showアクションを実装
tasks_contoroller.rb
def show
@task = Task.find(params[:id])
end
showのビュー実装
views/tasks/show.html.slim
編集機能の実装
・一覧と詳細画面に編集リンク追加
・newをコピーして、edit.htmlを作成
・editアクション実装
パーシャルでDRYに
・