LoginSignup
2
2

More than 5 years have passed since last update.

[Rails]FullCalendar カレンダー表示からイベント表示まで

Posted at

イベント表示までの記事が見つからなかったので書いてみます。

実現したいこと

FullCalendarの導入とイベントの表示

前提条件

FullCalendarのカレンダーは表示済み。
こちらを参考にしてください。

コード

私はホーム画面にその人の予定を表示させていますので、下記の様なコードになります。(slimで書いてます。)

home.html.slim

div.container.mt-5
  div id="calendar"

javascript:
  (function() {
    $('#calendar').fullCalendar({
      events: '/index.json'
  });

  }).call(this);

JavaScript部分はaseets/javascriptに入れたかったのですが、何故かそこに入れると表示されませんでした。
htmlにベタ打ちすると表示されるので、とりあえずここに入れています。

static_pages_controller.rb
def home
    if user_signed_in?
      @events = Event.where(user_id: current_user)
    end
 end

コントローラで必要なイベントを取得します。
今回の例の場合、名前の通りuserがサインイン済みだったら、現在のユーザーがスケジュールしているイベントをEventから取得します。
(user_signed_in?やcurrent_userは自分で実装してください。deviseというgemでログイン機能を実装すると自動で使える様になるメソッドです。)

home.js.jbuilder
json.array!(@events) do |event|
  json.id "#{event.id}"
  json.title "#{event.name}"
  json.start event.start_time
  json.end event.end_time
  json.url root_url(format: :html)
end

このファイルはhome.html.slimのviewと同じディレクトリに保存してください。これでjson形式でイベントを取得します。
必要なのはイベントのid、タイトル、開始時間、終了時間です。 開始時間、終了時間は今回DateTime型ですがTime型でもいけると思います。(未確認です。)

表示形式等、他にも色々といじれますが、とりあえずイベントはこれで表示されます。
コメント等ございましたら是非お願いします。
特に何でassets/javascriptにslimコードに書いたJavaScriptを入れると表示されなくなる理由とか分かる方がいると大変助かります。

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