はじめに
今回は、大まかな実装を説明して
別の記事で苦戦した場所などを記載したいと思います。
参考記事
機能の概要
今回カレンダーに下記の情報を登録,表示させます。
db
t.string "title"
t.datetime "time"
t.text "comment"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
実装手順
Gemfile
gem 'fullcalendar-rails'
bash
bundle install
Model作成
bin/railsrails g model Event title:string category:integer time:time comment:text
bin/rails db:migrate
EventModel設定
class Event < ApplicationRecord
validates :title, presence: true
validates :time, presence: true
#commentも必要なら設定をする。
end
routes.rbの設定
Rails.application.routes.draw do
root "events#index"
resources :events
#これは、date_detailsアクション(日にちの詳細)
get "events/dates/:date", to: "events#date_details", as: "event_date"
end
controllerの作成
bin/rails g controller Events
controller設定
class EventsController < ApplicationController
def index
@events = Event.all
respond_to do |format|
format.html
format.json do
render json: @events.map { |event|
{
id: event.id,
title: event.title,
start: event.time.in_time_zone("Asia/Tokyo").iso8601, # タイムゾーンを変換して送信
url: event_path(event)
}
}
end
end
end
def date_details
@date = params[:date]
Rails.logger.info "Date received: #{@date}"
@events = current_user.events
.where("DATE(time AT TIME ZONE 'UTC' AT TIME ZONE ?) = ?", "Asia/Tokyo", @date)
.order(time: :asc)
end
# --- 省略 ---
private
def event_params
params.require(:event).permit(:title, :time, :comment)
end
end
view実装
JavaScript(Tailwind + Stimulus.jsの場合)
bin/rails g stimulus calender
calender_controller.js
import { Controller } from "@hotwired/stimulus";
import { Calendar } from "@fullcalendar/core";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";
import jaLocale from "@fullcalendar/core/locales/ja";
export default class extends Controller {
connect() {
const calendar = new Calendar(this.element, {
plugins: [dayGridPlugin, interactionPlugin],
initialView: 'dayGridMonth',
timeZone: 'Asia/Tokyo',
locale: jaLocale,
events: '/events.json',
selectable: true,
editable: true,
dateClick: (info) => {
const date = new Date(info.date).toISOString().split("T")[0]; // UTC基準の日付を取得
window.location.href = `/events/dates/${date}`;
},
});
calendar.render();
}
}
view作成
touch app/views/events/index.html.erb
index.html.erb
<div id="calendar" data-controller="calendar"></div>
http://localhost:3000/events
こちらに飛ぶとcalenderが実装できているかと思います。