简体   繁体   中英

How do I use rails route helpers with jQuery?

I would like to use the jQuery ajax method $.get to access a restful route in rails. Something like this (keep in mind this is done in a haml template where I can use string interpolation):

$(function(){
  $(':radio').change(function(){
    $.get("#{edit_steps_path(N)}");  
  }
});

In the snippet above #{steps_path(N)} interpolates to the URL "\\steps\\N" and N is the value of the radio button that has been changed.

Obviously this doesn't work as the string interpolation happens on the server before the radio button can fire the change event. Clearly my approach to this problem is wrong altogether.

I've come up with some other ways of solving this problem, but none of them allow me to use the Rails route helpers or string interpolation, and I'm kind of bent on doing.

I'm guessing there is a proper way to accomplish what I'm seeking, just not sure what it is.

You can pass a "magic" token as id, then use javascript replace the token with the real id. Something like:

$(function(){
  $(':radio').change(function(){
    $.get("#{edit_steps_path('__id__')}".replace('__id__',$(this).data('rails-id));
  }
});

This assumes you have a data-rails-id attributes containing the rails id on the radio buttons. Of course such technique will not work for polymorphic url helpers.

You could use something like this:

  $(function(){
      $(':radio').change(function(){
        $.get("#{steps_path}/" + $(':radio:checked').val());
      }
    });

Which allows you to get the data via js.

However, this is probably not the best solution. Especially since you seem to be wanting to do a POST rather than a GET (from your question text).

And you are correct, you're whole method of dealing with this is probably flawed. Better (IMHO) to use JS and build a route structure that allows you to code your JS rather than trying to shoehorn route helpers into the mix. You can't use route helpers from JS the way you are trying to.

Why not do something like

<% steps.each_with_index do |step, n| %>
  <%= radio_button(object_name, method, steps_path(n)) %>
<% end %>

IE make the value of the radio button the url you want to submit to??

Nimai

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM