LoginSignup
18
21

More than 5 years have passed since last update.

【初心者向け】Rails5+FullCalendarでイベントを表示させる

Last updated at Posted at 2016-12-18

はじめに

今回は、FullCalendarでカレンダーをいい感じに出力して、そのカレンダーにDBに格納されたデータを出力する、というところまでをやります。

前提

前回の投稿で構築した環境を使っています。

FullCalendarでカレンダーを表示

toolboxをみるとicalendarが使われているんですね。
スクリーンショット 2016-12-14 0.21.31.png

今回は、fullcalendarから直接jsonを読み込ませて表示させようと思います。
よろしくお願いします。

ダウンロード & 設定

https://fullcalendar.io/download/ を読むとLatestVersionは3.1です。
CDNJSも用意されています。

Rails触ったこと無いので1から。。。
とりあえず、表示させていじりたいのでcontroller作成。

% bundle exec rails generate controller calendar index
Expected string default value for '--jbuilder'; got true (boolean)
Expected string default value for '--helper'; got true (boolean)
Expected string default value for '--assets'; got true (boolean)
      create  app/controllers/calendar_controller.rb
       route  get 'calendar/index'
      invoke  erb
      create    app/views/calendar
      create    app/views/calendar/index.html.erb
      invoke  rspec
      create    spec/controllers/calendar_controller_spec.rb
      create    spec/views/calendar
      create    spec/views/calendar/index.html.erb_spec.rb
      invoke  helper
      create    app/helpers/calendar_helper.rb
      invoke    rspec
      create      spec/helpers/calendar_helper_spec.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/calendar.coffee
      invoke    scss
      create      app/assets/stylesheets/calendar.scss
fukumura@ubuntu-xenial(15:31:59) ~/projects/dcalen

次はroute.rb。
route.rbの書き方はこの辺を参考にします。
http://railsguides.jp/routing.html

config/route.rb
Rails.application.routes.draw do
  root to: 'calendar#index'
  get 'calendar/index'
end

うつった。
まだ1行しか書いてない。

スクリーンショット 2016-12-14 0.40.17.png

さっそく読み込んで出力させてみます。

カレンダー表示

使い方はここを参考に。
https://fullcalendar.io/docs/

├── javascripts
│   ├── fullcalendar.3.1.0.js
│   ├── jquery.3.1.1.js
│   ├── moment.2.10.6.ja.js
│   └── moment.2.10.6.js
└── stylesheets
    └── fullcalendar.min.css

js、cssはこのように配置して、rails側で読み込ませるように。

スクリーンショット 2016-12-14 0.55.10.png

イベントテーブル作成

次にカレンダーに表示したいイベントのモデルを作ります。

% rails g model Event user_id:integer title:string disp_flg:boolean start:datetime end:datetime allDay created_at:datetime updated_at:datetime
Expected string default value for '--jbuilder'; got true (boolean)
      invoke  active_record
      create    db/migrate/20161218144626_create_events.rb
      create    app/models/event.rb
      invoke    rspec
      create      spec/models/event_spec.rb
% rails db:migrate
== 20161218144626 CreateEvents: migrating =====================================
-- create_table(:events)
   -> 0.0040s
== 20161218144626 CreateEvents: migrated (0.0041s) ============================

modelができました。

テーブルができたので、レコードも作ってみました。(手動)
スクリーンショット 2016-12-19 2.22.09.png

イベント表示

これらをjsonで出力させてfullcalendarに読み込ませてみます。

app/assets/javascripts/calendar.js
$(document).ready(function() {
    $('#calendar').fullCalendar({
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
      },
      navLinks: true,
      selectable: true,
      selectHelper: true,
      select: function(start, end) {
        var title = prompt('イベントを追加');
        var eventData;
        if (title) {
          eventData = {
            title: title,
            start: start,
            end: end
          };
          $('#calendar').fullCalendar('renderEvent', eventData, true);
        }
        $('#calendar').fullCalendar('unselect');
      },
      events: '/events.json',
      editable: true
    });
});

events: '/events.json',
ここで読み込みます。$.getJSON('/events.json'), って書いて取得できずに少しハマりました。
続いて、/events.json で eventsテーブルの値を返すようにします。

app/controllers/event_controller.rb
class EventController < ApplicationController
  def events
    @event = Event.all
    # render :json => @event
    respond_to do |format|
      format.json {
        render json:
        @event.to_json(
          only: [:title, :start, :end]
        )
      }
    end
  end
end

routeの設定もします。

config/routes.rb
Rails.application.routes.draw do
  root to: 'calendar#index'
  get 'calendar/index'
  get 'events', to: 'event#events'
end

表示されました。

スクリーンショット 2016-12-19 2.02.33.png

いろいろカスタマイズしたいですが、ちょっとずつ触りながら学んでいかせていただきます。

wipですが、ソースはこちら。

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