Recurring Events in Calendar - Rails

后端 未结 4 1935
清酒与你
清酒与你 2021-01-29 22:06

I am searching for the best way to model recurring events. I am using fullcalendar to display events. But I guess recurring events are best handled on the rails backend.

4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 22:41

    In my case I did something like this :

    # Holds most of my event's data; name, description, price ...
    class Event < ActiveRecord::Base
      has_many :schedules
      has_many :occurrences
      attr_accessible :started_at, :expired_at # expired_at is optional
    end
    
    # Holds my schedule object
    class Schedule < ActiveRecord::Base
      belongs_to :event
      attr_accessible :ice_cube_rule # which returns my deserialized ice_cube object
    end
    
    # Holds generated or manually created event occurrences 
    class Occurrence < ActiveRecord::Base
      belongs_to :event
      attr_accessible :started_at, :expired_at
      attr_accessible :generated # helps me tell which occurrences are out of an ice_cube generated serie
      attr_accessible :canceled_at
    end
    

    From there, I used ice_cube to manage the occurrences calculation and stored the results in the occurrences table. I first tried to work without the Occurrence model, but no matter how advanced the rule engine, you'll always have exceptions, so storing the occurrences in their own model gives you flexibility.

    Having an Occurrence model makes it a lot easier to display the events on a calendar or with date search filters as you just need to query for occurrences and then display the related event's data instead of gathering all the events in a given date range and then having to filter out the events where the schedule(s) don't match.

    Also you can flag an event occurrence as canceled or modify it (setting the generated attribute at false so it does not get cleaned up when editing an ice_cube schedule... or whatever your business need is)

    Of course if you have events that repeat indefinitely, you'll want to limit how far in the future you want those occurrences to be generated and use automated rake tasks to clean up the old ones and generate occurrences for the next year or so.

    So far this pattern works pretty well for me.

    Also, take a look at the recurring_select gem which is a pretty neat ice_cube form input.

提交回复
热议问题