Accessing rails routes in javascript

后端 未结 8 1689
星月不相逢
星月不相逢 2020-12-08 19:39

Can anyone explain how i can access the rails routes/names routes in javascript ?

The following are some of the things i tried http://github.com/jsierles/js_named_r

8条回答
  •  醉话见心
    2020-12-08 20:18

    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.

提交回复
热议问题