Wednesday, March 5, 2014

FullCalendar - Integration with Ruby On Rails

FullCalendar is a jQuery plugin that provides a full-sizeddrag & drop calendar like the one below. It uses AJAX to fetch events on-the-fly for each month and is easily configured to use your own feed format (an extension is provided for Google Calendar). It is visually customizable and exposes hooks for user-triggered events (like clicking or dragging an event). It is open source licensed under an MIT license.

Step 1 : Download the JQuery fullcalendar plugin by here and add fullcalender.js and fullcalender.css in to javascripts and stylesheets folder
or
fullcalendar is also available as a gem for Ruby on Rails which fits well with Asset Pipeline.

gem  'fullcalendar-rails'

Once the gem is installed, include fullcalendar javascript and css assets to your js and css file 

Step 2 : In view page index.html.erb or some other html.erb page add  a div with id 'calendar' 


<div id='calendar'></div>
Then add  following code to js file 

$(document).ready(function() {
  $("#calendar").fullCalendar({
    header: {
      left: "prev,next today",
      center: "title",
      right: "month,agendaWeek,agendaDay"
    },
    defaultView: "month",
    height: 500,
    slotMinutes: 15,
    events: "/dashboard/get_events",
    timeFormat: "h:mm t{ - h:mm t} ",
    dragOpacity: "0.5"
  });
});
Now we need to write a method to fetch Json data which we are going to display on calender 
In my example 
class DashboardController < ApplicationController
  respond_to :json
 def get_events
    @task = current_user.tasks
    events = []
    @task.each do |task|
      events << {:id => task.id, :title => "#{task.taskable.try(:name)} : #{task.task}", :start => "#{task.planned_start_date}",:end => "#{task.planned_end_date}" }
    end
    render :text => events.to_json
  end
end
DemoApp::Application.routes.draw do
   resources :dashboard do
      get :get_events, on: :collection
   end
end
that's it , now you can see calender in your dashboard


No comments:

Post a Comment