LoginSignup
0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2021-10-18

モデルの作成

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

ターミナル
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は1対多の関係
consultationのバリデーションは正規表現で作成(こちらで正規表現の確認ができます)
バリデーションを自作した場合は、validateにする必要があり

models/institution.rb
class Institution < ApplicationRecord
  has_many :consultationhours, dependent: :destroy
end
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を使用

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を介さないため、必要なデータを一緒に渡す

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
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を渡す

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>
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>

編集する

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>

日本時間に合わせる・時間の表示を設定する

config/application.rb
module SearchMedical
  class Application < Rails::Application
    config.time_zone  = "Tokyo"
  end
end
confing/initializers/time_formats.rb
Time::DATE_FORMATS[:stamp] = "%H:%M"

エラーメッセージを表示する

app/views/shared/_error.html.erb
<% if obj.errors.any? %>
  <% obj.errors.full_messages.each do |message| %>
    <ul>
      <li><%= message %></li>
    </ul>
  <% end %>
<% end %>
app/views/consultationhour/edit.html.erb
<%= render "shared/error", obj: @consultationhour %>

エラーメッセージを日本語化する

config/application.rb
config.i18n.default_locale= :ja
config/locals/ja.yml
ja:
  activerecord:
    attributes:
      consultationhour:
        start_time: "開始時間"
        end_time: "終了時間"

参考記事

Railsのルーティングをカスタマイズしたときのメモ
[Rails] dependent: :destroy について
Railsのrenderの書き方多すぎ問題について
別のコントローラをrenderする方法
Rails: ビューでstrftimeを直書きするのはたぶんよくない(翻訳)
【Rails】 Railsのバリデーションの使い方をマスターしよう!
簡単! Railsで過去の日付に対するバリデーションを設定してみた
Rails エラーメッセージの表示と日本語化

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0