Recurring database entries

95 Views Asked by At

Quick question about recurring DB entries.

Say I have users posting their Trips on a platform. Now, the user can say these Trips are recurring - she/he makes that trip every Tuesday and Thursday.

To make things even more interesting, say that every Trip has Requests attached to it, that other users can make. And they can make these Requests for every recurring trip.

Any ideas on how would I handle a case like this one on the back-end? Using Rails and Postgres.

Thanks in advance!

2

There are 2 best solutions below

0
On

Since every trip can have different requests, they all need their own individual ID. It would make sense to treat them exactly the same as non-recurring trips, except for one situation: when the creator of the trips wants to edit or delete all the instances of a recurring trip. For that, you may want to make an additional table for recurring trips, with a one-to-many relation from recurring trip IDs to trip IDs, and allow users to own recurring trip IDs as well as trip IDs. That way the user interface can display the two kinds logically and they won't get lost.

Just make sure that whenever a trip is edited or deleted, the recurring trip table is updated. That could either be accomplished by simply disallowing edits or deletion to trips that are part of a recurring trip, or make the trips table store an optional recurring trip ID.

3
On
User
  has_many :trips

Trip
  belongs_to :user
  has_many :requests

Request
  belongs_to :user
  belongs_to :trip

Add recurring_start and recurring_end attributes on Trip, and perhaps a recur attribute on Request. I don't know that you need to create any additional records for each Trip then, do you?

If so, you want your business logic handling that. Something like Sidekiq with a Query object that fetches Trips that are due for recurrence and creates the new trip with (for example) updated start and end dates…

class Trip < ApplicationModel
  scope :recurring, -> { where(recur: true) }
  scope :due_for_recurrence, -> { recurring.where(Trip.arel_table[:end_date].lt(Time.now)) }
end

You can use something like DeepCloneable if you want to automatically clone/dup associated records as well.