views:

47

answers:

2

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.

A: 

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.

Joshua Smith
The route helper puts a default value in the path if a parameter is not passed (ie: edit_step_path yields /steps/1/edit, where edit_step_path(12) yields /steps/12/edit. I need to pass in the id parameter for this to work.
rswolff
A: 

Why not do something like

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

I.E. make the value of the radio button the url you want to submit to??

Nimai

nimms
my code might be a bit out, I didn't proof read it, but you get the general idea.
nimms