link_to with jquery params in rails

pasine picture pasine · Nov 27, 2010 · Viewed 15k times · Source

I want to make an in-place search in my rails app.
I used button_to_remote with prototype, but now I'm using JQuery, so I changed to link_to.
This is my code:

<%= link_to "Search", {:action => "geocode", :with => "'address='+$('#{address_helper_id}').value"}, :method => :post, :remote => true %>

I want to pass the address textfield to my controller, but the output is not what I expected.

/mycontroller/geocode?with=%27address%3D%27%2B%24%28%27record_location___address%27%29.value

How do I submit my value?

Answer

theTRON picture theTRON · Dec 7, 2010

You might want to try approaching things a little more unobtrusively. I would recommend replacing your link_to call with something like:

<%= link_to "Search", "#", :id => "search_geocode", :"data-href" => my_controller_geocode_path %>

This is virtually identical to what you already have, except that it includes a unique id, and also the controller/geocode path in an data-href attribute. This will help allow you to keep your ruby and javascript a bit more separated.

Then in your application.js (or somewhere similar):

$('#search_geocode').live('click', function(event){
    event.preventDefault();
    $.post($(this).attr('data-href') + "?address=" + $('#address').val(), function(data){} );
});

What this is effectively doing is binding a click event listener to your search button, which posts the address to the url or path provided in the data-href attribute of your search link.

I also notice that in your code, you're setting the id of the source address in ruby. If this id attribute needs to change based on some sort of page template conditions, you could expand on my example by adding another data- parameter to your link. For example:

<%= link_to "Search", "#", :id => "search_geocode", :"data-href" => my_controller_geocode_path, :"data-address-id" => address_helper_id %>

And again, in application.js replacing above with something along the lines of:

$('#search_geocode').live('click', function(event){
    event.preventDefault();
    $.post($(this).attr('data-href') + "?address=" + $($(this).attr('data-address-id')).val(), function(data){} );
});