Using Drag-and-Drop to Reorder Slides
The scaffolding we have for editing a slideshow shows just the slideshow attributes that are stored directly in the slideshows table: the slideshow’s name and the creation date. The most important part is missing: the photos that are part of the slideshow!
By now, you’ve probably realized that this is because the scaffolding code deals with only one database table: the slideshows table. The relationship data about which photos are assigned to a slideshow and their order in the slideshow are stored in the slides table. Let’s remedy that problem by adding some Ajax code to deal with slides and the order of the slides.
We’re going to display a list of thumbnails of all the photos that are in a slideshow, and then let the user reorder them using drag-and-drop. If you’ve had to struggle through implementing drag-and-drop before, you’re not going to believe how easy this is going to be. Here’s a hint: this will take fewer than 50 additional lines of the Ruby, CSS, and ERb template!
Let’s start by reviewing the current implementation of the edit
action in the slideshow controller:
def edit @slideshow = Slideshow.find(params[:id]) end
This action expects to find the id
of the
slideshow to edit passed in as the id
parameter, which is normally decoded from the URL. You’ll find the
slideshow with that id
and assign that slideshow object
to the instance variable @slideshow
so
that it can be accessed in the view template.
That is really all that’s needed here, ...
Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.