All threads / Drag and Drop sortable lists with Rails & Stimulus JS Discussion

Ask A Question


You’re not receiving notifications from this thread.

Drag and Drop sortable lists with Rails & Stimulus JS Discussion

Chris, thank you so much for this! I was actually going through the old drag and drop tutorial yesterday and today to update it for Rails 6.

I seem to be having an issue both with this tutorial and the other where the Rails.ajax line in both of them is causing the error message:

Uncaught ReferenceError: Rails is not defined

In the old tutorial, I was able to get it to work by changing Rails.ajax to $.ajax but that only works with jQuery and not Stimulus. Do you know what might be causing this?

Add import Rails from "@rails/ujs"; to the top of your drag_controller.js file and it should work fine.

I believe Chris starts apps with his Jumpstart template, which includes this by default.

Tim, you may need to register Rails globally inside webpack config. Than you will not need to import it inside every controller.

// config/webpack/environment.js

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

  new webpack.ProvidePlugin({
    Rails: ['@rails/ujs']

module.exports = environment

Thanks John and Dino! That fixed both the old and new versions. I've been trying to figure that out for awhile now. Much appreciated!


What would this look like when used with Stimulus Reflex?


I've got a question on this. What if the todo is nested within another model. Like todolist has many todos. I'm having trouble setting up the data-drag-url to be something like /todolist/:id/todos/:id/move. How do you bring the todolist :id?

hey, I have an image model. image belongs to product, and product has many images. this is how I did it.

<div data-controller="drags" data-drags-url="/products/:product_id/images/:id/move">

and in the stimulus controller, I replaced the url by this

let id =
    let product_id = event.item.dataset.productId

    let data = new FormData()
    data.append("position", event.newIndex + 1)

    let url ="url")
    let mapUrl = { product_id: product_id, id: id}

    url = url.replace(/product_id|id/gi, function(matched){
      return mapUrl[matched];

      url: url,
      type: 'PATCH',
      data: data
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 35,699+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.