I'm creating a trip planner application using rails 4, coffeescript, the Google Maps API, and jquery. On our trip planner page, we let users link multiple destinations together on a Google map, and save the trip to their account if they want.
We have 3 main models we are working with:
Trips - contains the name of the trip, start and end dates
Destinations - locations on the map, identified by a name and geo coordinates (lat/long). Destinations are not directly linked to a trip.
DestinationOrders - this is the table contains the order of destinations in a trip (like a linked list). The columns are trip_id, destination_id, and order_authority. Order_authority will be a number we use to sort the order of destinations using the method described here.
A typical set of actions on the page are:
- Load the google map
- Select the first destination using Google's places autocomplete functionality (javascript). Add a marker to the Google Map for the first destination
- Add a second destination, place the marker, link the two destinations with a path
- Add a third destination, place the marker, link destinations 2 and destination 3 with a path
- User clicks 'Save' to store the trip in his account
We are fairly new to rails and I'm wondering the best way to approach this given the back and forth between javascript, the controller, and the model. We don't want to associate the trip to his account until he click save.
Possible approaches we've thought of:
Do we create new instances of the models, then when the user clicks save, save all of the instances to the database? The problem here is when trying to create the DestinationOrder
, as it requires a trip id and a destination id which have not been created yet. Using our steps above, this would be something like:
trip = Trip.new
- Send location information (place) to controller via Ajax, then:
firstDestination = Destination.new (name: place.name, lat: place.geometry.location.lat, long: place.geometry.location.long)
firstDestOrder = DestinationOrder.new
Another possible (naive) solution would be to keep everything stored in javascript variables until the user clicks save, then send an ajax request with all of the destinations in order and create the models.
Finally, we thought of the possibility of creating and saving trips and destinations as the user goes along. That is, when a user first gets to the page, a trip would be created and saved. When the user adds a destination, that destination would be saved as well. This allows us to pass DestinationOrder
those id, and if the user clicks save, we would associate the trip_id
with his account. However, if the user left the site mid-creation, this would create a zombie trip with no associated user, and would require some process to clean these up every-so-often.
What is the most efficient way to approach a situation like this? I hope my explanation makes sense - please let me know if I need to clarify. Any help is appreciated!