施設の営業時間を作成・登録する

## モデルの作成
営業時間を作成、編集するためのモデルを作成

```ruby:ターミナル
rails g model Consultationhour start_time: time, end_time: time, monday: string, ... holiday: string, detail: string, instituion_id: integer

rails db:migrate
rails g controller Consultationhours create
```
## モデルの設定
institutionとconsultationhourは１対多の関係
consultationのバリデーションは正規表現で作成([こちらで正規表現の確認ができます](https://rubular.com/))
バリデーションを自作した場合は、``validate``にする必要があり

```ruby:models/institution.rb
class Institution < ApplicationRecord
  has_many :consultationhours, dependent: :destroy
end
```
```ruby:models/consultationhour.rb
class Consultationhour < ApplicationRecord
  belongs_to :institution

  validates :start_time, presence: true, format: { with: /[[0-2]0-9]:[0-5][0-9]/, message: "は[00:00]の形式で入力してください" }
  validates :end_time, presence: true, format: { with: /[[0-2]0-9]:[0-5][0-9]/, message: "は[00:00]の形式で入力してください" }
  validate :before_start_time

  def before_start_time
    if start_time != nil && end_time != nil
      if end_time < start_time
        errors.add(:end_time, "は開始時間よりも後に設定してください")
      end
    end
  end
end
```
## ルーティングの設定
institutionのidをconsultationhourに渡すため、memberを使用

```ruby:config/routes.rb
Rails.application.routes.draw do
  resources :institutions do
    member do
      get "consultationhour"
    end
  end
  resources :consultationhours
end
```
## コントローラーの設定
institution#showに登録したconsultationhoursを一緒に表示
institution#consultationhourでconsultationhourを新規作成
renderはmodelを介さないため、必要なデータを一緒に渡す

```ruby:app/controllers/institution.rb
class InstitutionsController < ApplicationController
  def show
    @institution = Institution.find(params[:id])
    @consultationhours = @institution.consultationhours
  end

  def consultationhour
    @institution = Institution.find(params[:id])
    @consultationhour = Consultationhour.new
  end
end
```
```ruby:app/controllers/consultationhour.rb
class ConsultationhoursController < ApplicationController
  def create
    @consultationhour = Consultationhour.new(consultationhour_params)
    institution_id = @consultationhour.institution_id
    if @consultationhour.save
      redirect_to institution_path(@consultationhour.institution_id), notice: "診療時間を追加しました"
    else
      @institution = Institution.find(institution_id)
      render template: "institutions/consultationhour"
    end
  end

  def edit
    @consultationhour = Consultationhour.find(params[:id])
  end

  def update
    @consultationhour = Consultationhour.find(params[:id])
    if @consultationhour.update(consultationhour_params)
      redirect_to institution_path(@consultationhour.institution_id), notice: "診療時間を更新しました"
    else
      @consultationhour.start_time = "00:00" if @consultationhour.start_time.nil?
      @consultationhour.end_time = "00:00" if @consultationhour.end_time.nil?
      render "edit"
    end
  end

  def destroy
    @consultationhour = Consultationhour.find(params[:id])
    @consultationhour.destroy
    redirect_to institutions_path, notice: "診療時間を削除しました"
  end
end

private

def consultationhour_params
  params.require(:consultationhour).permit(:start_time, :end_time, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday, :holiday, :detail, :institution_id)
end
```
## Viewの設定
### 新規作成
hidden_fieldにinstitution.idを入れて、consultationhourにinstitution.idを渡す

```erb:institutions/show.html.erb
<div>
  <div>
    <h2>医療機関情報</h2>
    <div>
      <div>診療時間</div>
      <table>
        <tr>
          <th>時間</th>
          <th>月</th>
          <th>火</th>
          <th>水</th>
          <th>木</th>
          <th>金</th>
          <th>土</th>
          <th>日</th>
          <th>祝</th>
          <th>編集</th>
          <th>削除</th>
        </tr>
        <% if @consultationhours.exists? %>
          <% @consultationhours.each do |consultationhour| %>
            <tr>
              <td><%= consultationhour.start_time.to_s(:stamp) %> - <%= consultationhour.end_time.to_s(:stamp) %></td>
              <td><%= consultationhour.monday %></td>
              <td><%= consultationhour.tuesday %></td>
              <td><%= consultationhour.wednesday %></td>
              <td><%= consultationhour.thursday %></td>
              <td><%= consultationhour.friday %></td>
              <td><%= consultationhour.saturday %></td>
              <td><%= consultationhour.sunday %></td>
              <td><%= consultationhour.holiday %></td>
              <td><%= link_to "修正", edit_consultationhour_path(consultationhour.id) %></td>
              <td><%= link_to "削除", consultationhour, method: :delete, data: {confirm: "本当に削除しますか"} %></td>
            </tr>
          <% end %>
        <% else %>
          <div>診療時間が登録されていません</div>
        <% end %>
      </table>
      <div>
        <% if @consultationhours.exists? %>
          <% @consultationhours.each do |consultationhour| %>
            <%= consultationhour.detail %><br>
          <% end %>
        <% end %>
      </div>
    </div>
    <div><%= link_to "診療時間を登録する", consultationhour_institution_path(@institution.id) %></div>
  </div>
</div>
```
```erb:institutions/consultationhour.html.erb
<div>
  <h2>診療時間作成</h2>
  <%= form_with model: @consultationhour do |f|%>
    <div>
      <%= f.label :start_time, "開始時間" %>
      <%= f.text_field :start_time %>
    </div>
    <div>
      <%= f.label :end_time, "終了時間"%>
      <%= f.text_field :end_time%>
    </div>
    <div>
      <div>
        <%= f.label :monday, "月曜日" %>
        <%= f.select :monday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :tuesday, "火曜日" %>
        <%= f.select :tuesday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :wednesday, "水曜日" %>
        <%= f.select :wednesday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :thursday, "木曜日" %>
        <%= f.select :thursday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :friday, "金曜日" %>
        <%= f.select :friday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :saturday, "土曜日" %>
        <%= f.select :saturday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :sunday, "日曜日" %>
        <%= f.select :sunday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :holiday, "祝日" %>
        <%= f.select :holiday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
    </div>
    <div>
      <%= f.label :detail, "詳細" %>
      <%= f.text_area :detail %>
    </div>
    <%= f.hidden_field :institution_id, value: @institution.id %>
    <div>
      <%= f.submit "登録する" %>
    </div>
  <% end %>
  <div>
    <%= link_to "医療機関情報へ戻る", institution_path(@institution.id) %>
  </div>
</div>
```
### 編集する
```erb:consultationhours/edit.html.erb
<div>
  <h2>診療時間編集</h2>
  <%= form_with model: @consultationhour do |f|%>
    <div>
      <%= f.label :start_time, "開始時間" %>
      <%= f.text_field :start_time, value: @consultationhour.start_time.to_s(:stamp) %>
    </div>
    <div>
      <%= f.label :end_time, "終了時間"%>
      <%= f.text_field :end_time, value: @consultationhour.end_time.to_s(:stamp) %>
    </div>
    <div>
      <div>
        <%= f.label :monday, "月曜日" %>
        <%= f.select :monday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :tuesday, "火曜日" %>
        <%= f.select :tuesday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :wednesday, "水曜日" %>
        <%= f.select :wednesday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :thursday, "木曜日" %>
        <%= f.select :thursday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :friday, "金曜日" %>
        <%= f.select :friday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :saturday, "土曜日" %>
        <%= f.select :saturday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :sunday, "日曜日" %>
        <%= f.select :sunday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
      <div>
        <%= f.label :holiday, "祝日" %>
        <%= f.select :holiday, [["-", "-"], ["●", "●"], ["※", "※"]] %>
      </div>
    </div>
    <div>
      <%= f.label :detail, "詳細" %>
      <%= f.text_area :detail %>
    </div>
    <div>
      <%= f.submit "更新する" %>
    </div>
  <% end %>
  <div>
    <%= link_to "医療機関情報へ戻る", institution_path(@institution.id) %>
  </div>
</div>
```

## 日本時間に合わせる・時間の表示を設定する
```ruby:config/application.rb
module SearchMedical
  class Application < Rails::Application
    config.time_zone  = "Tokyo"
  end
end
```
```ruby:confing/initializers/time_formats.rb
Time::DATE_FORMATS[:stamp] = "%H:%M"
```
## エラーメッセージを表示する
```erb:app/views/shared/_error.html.erb
<% if obj.errors.any? %>
  <% obj.errors.full_messages.each do |message| %>
    <ul>
      <li><%= message %></li>
    </ul>
  <% end %>
<% end %>
```
```erb:app/views/consultationhour/edit.html.erb
<%= render "shared/error", obj: @consultationhour %>
```
## エラーメッセージを日本語化する
```ruby:config/application.rb
config.i18n.default_locale= :ja
```
```yml:config/locals/ja.yml
ja:
  activerecord:
    attributes:
      consultationhour:
        start_time: "開始時間"
        end_time: "終了時間"
```
## 参考記事
[Railsのルーティングをカスタマイズしたときのメモ](https://qiita.com/dkurata38/items/273f380853f24bc69da8)
[[Rails] dependent: :destroy について](https://qiita.com/Tsh-43879562/items/fbc968453a7063776637)
[Railsのrenderの書き方多すぎ問題について](https://qiita.com/bSRATulen2N90kL/items/7fd384b640d650a8070a)
[別のコントローラをrenderする方法](https://ihatov08.hatenablog.com/entry/2016/02/26/130212)
[Rails: ビューでstrftimeを直書きするのはたぶんよくない（翻訳）](https://techracho.bpsinc.jp/hachi8833/2019_11_21/82301)
[【Rails】 Railsのバリデーションの使い方をマスターしよう！](https://pikawaka.com/rails/validation)
[簡単！ Railsで過去の日付に対するバリデーションを設定してみた](https://kossy-web-engineer.hatenablog.com/entry/2018/10/08/033659)
[Rails エラーメッセージの表示と日本語化](https://qiita.com/satreu16/items/a072a4be415f30087ed7)