Help us understand the problem. What is going on with this article?

初めてのfullcalendar

More than 3 years have passed since last update.

この前fullcalendar触ったので、その時のロジックをメモ。

Gemfileに追加

Gemfile.rb
 gem 'fullcalendar-rails'
 gem 'momentjs-rails'

jsに追記

app/assets/javascripts/application.js
 //= require moment
 //= require fullcalendar
 $(document).ready(function() {
    $('#calendar').fullCalendar({
       events:window.hoge_datas
    })
});

コントローラでデータ取得&成形

app/controllers/hoge_controller.rb
def index
    #表示内容取得
    hoge_datas = Hoge.find_by_sql([
      'select * from hoge where hoge_id = ?',params[:hoge]
      ])
    #表示用データ成形
    @datas = [];
    hoge_datas.each do |data|
      @datas += [
        'title' => data['title'],     #"クリスマス!"
        'start' => data['start_time'],#"2015-12-24 00:00:00"
        'end'   => data['end_time'],  #"2015-12-25 24:00:00"
        'detail'=> data['detail'],    #"detail"
        'color' => 'red'
        ]
    end

ビューからjsにjson形式で値を渡し、呼び出す

app/views/hoge/hoge.html.erb
 <%= javascript_tag do %>
   window.hoge_datas = <%= raw @datas.to_json %>;
 <% end %>

 <div id="calendar"></div>

動くとこんな感じになる。(12aはAM:12の意味らしい)
fullcalendar.jpg

おわり

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away