Bulk Operations in Rails Discussion
For those of you who want to use fetch instead of Rails.ajax:
let token = document.querySelector('meta[name="csrf-token"]').content;
fetch(/your/path
, {
method: "DELETE",
headers: {
"X-CSRF-Token": token,
},
body: data,
}).then((response) => {
if (response.redirected) {
window.location.href = response.url;
}
});
FYI, for anyone that is on the default Rails 7 / Hotwire setup and needs to tweak this, here are a few things that I needed to do to get this working:
Note that your data controllers, targets, and actions no longer use the . syntax that Chris used at the time of the video. That has been deprecated. You'll need to make sure they match the style as outlined here: https://www.stimulus-components.com/docs/stimulus-checkbox-select-all/. Such as
data-checkbox-select-all-target="checkboxAll"
Make sure to use
super.connect()
in your stimulus controller to inherit fromstimulus-select-all
:
connect() {
super.connect()
}In order to use request.js instead of Rails.ajax, your stimulus controller should have
import { destroy } from '@rails/request.js'
and the request can look like something like this:
destroy('/notifications/bulk', { body: data, responseKind: "turbo-stream" })
Note that I had to include the turbo-stream responseKind to get it to work.
- Last, but not least, don't forget to use
status: :see_other
in your bulk_controller.rb redirect. Mine ended up looking like this:
def destroy
@notifications.destroy_all
respond_to do |format|
format.html { redirect_to notifications_url, status: :see_other }
end
end
For anyone in the future who wants to get this to work with turbo, you will have to convert the FormData into a query string, and append that string to a form action (In my case I used the button_to tag). This way the fetch remains within turbo.
Hi! I'm having an issue with typescript in vscode complaining about missing @type file. Already burned trying to use the library in latest rails 7 project. I'd publish the @type in yarn, is it possible?? Any tutorial??
I was actually struggling at setting config.assets.debug = true
in Rails 7 to get Stimulus logs properly. The warning exists but esbuild doesn't really care about it.
Hello Chris, I'm trying to use this on my other sets of data. For Posts Table it worked but not for other Table I named "Data" and I've created another controller under javascript/controllers/data_bulk_controller. Along with data/bulk_controller.rb. and created the name space in the routes.rb file. If you could help me with this that would be great! thank you!