UJS compat library for Ruby on Jets and API Gateway.
The @rails/ujs package adds unobtrusive JavaScript scripting support for Rails. This is typically done with:
yarn add @rails/ujs
Call rails ujs code:
app/javascript/packs/application.js
import Rails from "@rails/ujs"
Rails.start()
- The
@rails/ujs
package registers click handlers to links with thedata-delete
attribute. Example:<a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/posts/123">Destroy</a>
- When the link is clicked,
@rails/ujs
creates a hidden form and submits the request as aPOST
request with a hidden field_method=delete
. - The Rack::MethodOverride middleware is used to then adjust
POST
toDELETE
request appropriately.
Essentially, a DELETE http request is mimiced using a POST http request. It all happens transparently, so developers don't really notice the magic happening behind the scenes.
Unfortunately API Gateway REST APIs require actual DELETE requests to the resource, not mimiced POST requests. Example:
DELETE /posts/123
Sending a POST /posts/123
with a _method=delete
will not work with API Gateway because the POST /posts/123
route points to the posts#update
method API Gateway.
To fix the issue, this javascript library adds click handlers that intercept @rails/ujs
handlers and sends an AJAX DELETE request correctly.
yarn add @rubyonjets/ujs-compat
And then add the Jets ujs-compat code below the Rails ujs code.
app/javascript/packs/application.js
import jquery from 'jquery'
window.$ = jquery
import Jets from "@rubyonjets/ujs-compat"
Jets.start()
This package is dependencies on jquery. You should configure your own jquery.
- Considered putting
POST /posts/123
to theposts#delete
action instead ofposts#update
. But that feels like unexpected behavior. - Considered adding logic at the lambda handlers processing logic to convert
posts#update
actions with_method=delete
to callposts#delete
. This will make the logic closer to whatRack::MethodOverride
does but again feels a little bit confusing. - So went with javascript library to handle things earlier. An actual DELETE request is sent via AJAX to API Gateway.
- Open to suggestions and improvements.