如何在rails中正确使用Fullcalendar jQuery插件

前端之家收集整理的这篇文章主要介绍了如何在rails中正确使用Fullcalendar jQuery插件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在rails 4中使用gem’fullcalendar-rails’来使用 jquery fullcalendar,顺便说一下我是rails的新手,我花了很多天试图做这个工作,但我找不到指南从日历到rails中的控制器执行适当的发布,然后将其保存到数据库中.

我试过这个指南,但似乎没有什么工作正常,有谁知道怎么做?

http://www.rkonrails.com/blog/2013/10/full-calendar-rails-jquery-full-calendar-in-rails/

http://blog.crowdint.com/2014/02/18/fancy-calendars-for-your-web-application-with-fullcalendar.html

其实这是我的代码

事件模型

class Event < ActiveRecord::Base
    def self.between(start_time,end_time)
      where('starts_at > :lo and starts_at < :up',:lo => Event.format_date(start_time),:up => Event.format_date(end_time)
      )
    end

    def self.format_date(date_time)
     Time.at(date_time.to_i).to_formatted_s(:db)
    end

    def as_json(options = {})
      {
        :id => self.id,:title => self.title,:description => self.description || "",:start => starts_at.rfc822,:end => ends_at.rfc822,:allDay => self.all_day,:recurring => false,:url => Rails.application.routes.url_helpers.event_path(id)
      }
    end
  end

事件控制器

class EventsController < ApplicationController
  def new
    @event = Event.new
    respond_to do |format|
      format.html # new.html.erb
      format.js
    end
  end

  def create
    @event = Event.new params['event']

    if @event.save
      render nothing: true
    else
      render :json => { },:status => 500
    end
  end

  def index
    @events = Event.between(params['start'],params['end']) if (params['start'] && params['end']) 
    respond_to do |format| 
      format.html # index.html.erb 
      format.json { render :json => @events } 
    end
  end
end

CALENDAR.JS.COFFEE

$(document).ready -> 
  $('#calendar').fullCalendar 
    editable: false,columnFormat: {
      month: 'dddd',week: 'dddd d',day: 'ddd' 
    }
    buttonText: {
      today:    'today',month:    'month',week:     'week',day:      'day'
    }

    minTime: "08:00:00"
    maxTime: "23:00:00"
    header:
      left: 'prev,next today',center: 'title',right: ''
    firstDay: 1


    selectable: true
    selectHelper: true
    select: (start,end) ->
      title = prompt("Event Title:")
      eventData = undefined
      if title
        eventData =
          title: title
          start: start
          end: end
        $("#calendar").fullCalendar "renderEvent",eventData,true # stick? = true
      $("#calendar").fullCalendar "unselect"


    defaultView: 'agendaWeek',allDaySlot: false,height: 500,slotMinutes: 30,eventSources: [{ 
      url: '/events',}],timeFormat: 'h:mm t{ - h:mm t} ',dragOpacity: "0.5" 
    eventDrop: (event,dayDelta,minuteDelta,allDay,revertFunc) -> 
      updateEvent(event); 
    eventResize: (event,revertFunc) -> 
      updateEvent(event); 

updateEvent = (the_event) -> 
  $.update "/events/" + the_event.id,event: 
      title: the_event.title,starts_at: "" + the_event.start,ends_at: "" + the_event.end,description: the_event.description

事件移民

create_table "events",force: true do |t|
    t.string   "title"
    t.string   "starts_at"
    t.string   "ends_at"
    t.string   "description"
    t.string   "allDay"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

解决方法

所以,经过大量的研究,我发现了使用rails运行fullcanlendar的正确方法,所以我会告诉你代码.这是使用周历的示例.

如果您的语言是英语,则忽略名称的更改,但如果不是,则可以使用它将其更改为您的语言. monthNames,monthNamesShort,dayNames,dayNamesShort和buttonText中的“今天”按钮.

在“用户名”中,您可以验证您想要的任何内容,例如标题或其他参数.

calendar.js

var updateEvent;

$(document).ready(function() {
  var todayDate = new Date();
  todayDate.setHours(0,0);

  $('#calendar').fullCalendar({
    editable: false,slotEventOverlap: false,monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'],dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],dayNamesShort: ['Dom','Lun','Mié','Jue','Vie','Sáb'],day: 'ddd'
    },buttonText: {
      today: 'Hoy',month: 'month',week: 'week',day: 'day'
    },minTime: "08:00:00",maxTime: "23:00:00",header: {
      left: 'prev,right: ''
    },firstDay: 1,//this section is triggered when the event cell it's clicked
    selectable: true,selectHelper: true,select: function(start,end) {
      var user_name;
      user_name = prompt("User name: ");
      var eventData;
      //this validates that the user must insert a name in the input
      if (user_name) {
        eventData = {
          title: "Reserved",start: start,end: end,user_name: user_name
        };
        //here i validate that the user can't create an event before today
        if (eventData.start < todayDate){
          alert('You can't choose a date that already past.');
          $("#calendar").fullCalendar("unselect");
          return
        }
        //if everything it's ok,then the event is saved in database with ajax
        $.ajax({
          url: "events",type: "POST",data: eventData,dataType: 'json',success: function(json) {
            alert(json.msg);
            $("#calendar").fullCalendar("renderEvent",true);
            $("#calendar").fullCalendar("refetchEvents");
          }
        });
      }
      $("#calendar").fullCalendar("unselect");
    },defaultView: 'agendaWeek',eventSources: [
      {
        url: '/events'
      }
    ],dragOpacity: "0.5"
  });
};

在事件模型中有4个属性是使其工作所必需的,它们是start,end,title和allDay变量.

as_json方法数据库获取每个事件并将其格式化发送到日历中的每个单元格,因此“url”属性将是每个事件“show”的链接,因此如果您单击该链接,它将发送给您视图(在此示例中不是).

event.rb(型号)

class Event < ActiveRecord::Base

  # scope :between,lambda {|start_time,end_time| {:conditions => ["? < starts_at and starts_at < ?",Event.format_date(start_time),Event.format_date(end_time)] }}
  def self.between(start_time,end_time)
    where('start_at > :lo and start_at < :up',:up => Event.format_date(end_time)
    )
  end

  def self.format_date(date_time)
   Time.at(date_time.to_i).to_formatted_s(:db)
  end

  def as_json(options = {})
    {
      :id => self.id,:start => start_at.rfc822,:end => end_at.rfc822,:allDay => allDay,:user_name => self.user_name,:url => Rails.application.routes.url_helpers.events_path(id),:color => "green"
    }
  end
end

这里没有什么可以添加的,代码是不言自明的.

events_controller.rb

class EventsController < ApplicationController
  def new
    @event = Event.new
    respond_to do |format|
      format.html
      format.js
    end
  end

  def create
    @event = Event.new(event_params)

    if @event.save
      render json: {msg: 'your event was saved.'}
    else
      render json: {msg: 'error: something go wrong.' },status: 500
    end
  end

  def index
    @events = Event.between(params['start'],params['end']) if (params['start'] && params['end']) 

    respond_to do |format| 
      format.html
      format.json { render :json => @events } 
    end
  end

  def event_params
    params.permit(:title).merge start_at: params[:start].to_time,end_at: params[:end].to_time,user_name: params[:user_name]
  end

创建事件迁移

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :title
      t.datetime :start_at
      t.datetime :end_at
      t.string :allDay
      t.string :user_name

      t.timestamps
    end
  end
end

使用此示例,您可以在rails中保存和显示事件而不会出现问题,但如果您想要更改事件中数据的显示方式,我建议您更改日历的css属性,例如:

如果您只想在没有开始和结束时间的事件中显示标题,则必须执行以下操作:

.fc-event-time {
  display: none;
}

如果你想把标题集中在一起:

.fc-event-title{
  text-align: center;
}

正如您所看到的那样非常简单,您无需更改fullcalendar的原始代码.

希望能帮助到你!! :d!

原文链接:/jquery/175616.html

猜你在找的jQuery相关文章