Search code examples
javascriptruby-on-railsrubyajaxrails-routing

How to use rails paths in js files for GET's and ajax calls?


I have a link that toggles description lengths between short and long.

Initially I created it with a call from a js file, i.e. just

# /app/assets/javascripts/toggle_length.js
$.get('/toggle_full_details');

That works fine. (it uses css classes to show/hide long and short descriptions).

But ideally I want to use a rails route for the link.

Which are (partial listing for relevant route):

$ rake routes
    Prefix               Verb  URI Pattern                     Controller#Action
    ...
    toggle_full_details  GET   /toggle_full_details(.:format)  links#toggle_full_details
    toggle_row_shading   GET   /toggle_row_shading(.:format)   links#toggle_row_shading
    ...
    root                 GET   /                               links#index

So I renamed my long_or_sort_details.js file to be long_or_short_details.js.erb and tried using a rails route but none of the below attempts worked, what am I missing / doing wrong?

$.get({ "<%= toggle_full_details_path %>" }) 
// Gave: undefined local variable or method toggle_full_details_path

$.get({"<%= toggle_full_details_url %>"}); 
// Gave: undefined local variable or method toggle_full_details_url

$.ajax({url:"/toggle_full_details", type: 'GET' }) 
// Works ok... but not using routes :(

$.ajax({ url:'<%= toggle_full_details_path %>', type: 'GET' }) 
// undefined local variable or method `toggle_full_details_path'

fyi my app/assets/javascripts/applications.js includes the file with

//= require long_or_short_details

Solution

  • This worked for me:

    $.get("<%= Rails.application.routes.url_helpers.toggle_full_details_path %>"); 
    

    I don't want any user message if the call fails, hence no $.ajax and success: or failure: calls.

    If I had wanted additional stuff for success or failure one could use something like:

    $.ajax({
      url: "<%= Rails.application.routes.url_helpers.toggle_full_details_path %>",
      type: 'GET',
      success: function(r) {
        $('span#messages').html('<span class="ok">yes</span>');
      },
      error: function(r) {
        $('span#messages').html('<span class="not_ok">no</span>');
      }
    });