Accessing rails routes in javascript

Viewed 30291
8 Answers

If you are using a JS pipeline that supports import (ES6 + webpacker), you might want to check out js_from_routes, a code-generation library that works seamlessly with Rails reloader.

For each endpoint that you'd like to access from JS, it will generate a method that can help you build a URL or make a request.

resources :video_clips, only: [:update], export: true

By using it in combination with axios, these generated helpers can be convenient and easy to use:

import VideoClipsRequests from '@requests/VideoClipsRequests'

VideoClipsRequests.update({ data: video })
  .then(onVideoUpdate)

Have in mind that you can adjust the generated code by providing a custom template, so it can adapt to any technology you are using, even plain jQuery.

Benefits:

  • No need to manually specify the URL, preventing mistakes and saving development time.
  • If an action is renamed or removed, the helper ceases to exist, which causes an error that is easier to detect than a 404.
Related