Rails4.1.6でGoogle Calendar API v3とfullcalendarに新規で予定を反映させる方法
fullcalendarの情報が日本語だと少ないのでみなさんと共有できればと思います。
参考人なりましたら幸いです。
fullcalendarにイベントの登録する方法。
空いている時間帯をクリックして登録するまでの処理の流れ
1.空いている時間をクリックするとタイトルの入力画面がモーダルで出る
2.タイトルを入力して『OK』ボタンを押す
3.GoogleCalendarとfullcalendar両方に反映させる
大きく分けてこの3つになります。
クリックした時の処理
fullcalendarの空いている時間をクリックした時の処理は
select:
を使います。
ちなみに他のクリックイベントは
月のカレンダーで空いている日に終日予定を入れる場合 => dayClick
イベントをクリックした場合(更新とか削除の時に使用)=> eventClick
にそれぞれ処理を書きます。
今回は新しく週カレンダーに時間単位で予定を登録してみます。
selectイベントの処理を書く
calendar.js
select: function(start, end, allDay) { var title = prompt('タイトルを入力してください'); if (!allDay) { $('#calendar').fullCalendar('renderEvent', { title: title, start: start, end: end, color: 'pink', allDay: false }); } else { $('#calendar').fullCalendar('renderEvent', { title: title, start: start, end: end, color: 'pink', allDay: allDay }); }; $('#calendar').fullCalendar('unselect'); $.ajax({ url: '/api/gcals/create_event_self', type: 'POST', dataType: 'json', data: { title: title, start: start, end: end }, }) },
終日をクリックしたかどうかで条件分岐しています。
fullcalendarにイベントを表示させるのはrenderEventです。
まずはrenderEventでクリックした時間帯の色を変えて分かり易くします。
そのあとGooogleCalendarApiにAjaxで投げてGoogleCalendarにも
反映させます。
続いて2、3の処理
gcals_controller.rb
def create_event_self event = [ current_user[:email], params[:title], params[:start], params[:end] ] #UserのGmailが必要になるのでcurrent_user[:email]でmodelに渡す new_event = Gcal.new.insert_event(event) end
gcal.rb
def insert_event(event) #UserのGmailを受け取るので引数が必要 email = event[0] start_time = DateTime.parse(event[2]) end_time = DateTime.parse(event[3]) event_resorces = { 'summary' => event[1],#fullcalendarのtitle 'start' => { 'dateTime' => start_time }, 'end' => { 'dateTime' => end_time }, } result = @client.execute(:api_method => @service.events.insert, :parameters => {'calendarId' => email }, :body => JSON.dump(event_resorces), :headers => {'Content-Type' => 'application/json'}) end
routes.rb
post 'gcals/create_event_self' => 'gcals#create_event_self'
これで好きな時間帯にイベントを登録できるようになりました!
なお初心者のため、もっとこう書いた方が良いなどございましたら
ご指摘いただけると嬉しいです。