Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unobtrusive jQuery autocomplete in Rails

I'm using rails, but doing all my Javascript unobtrusively using jQuery in application.js.

Unfortunately, this makes it quite difficult to reference URLs. For example, if I want to give a field autocomplete behavior, I have to hard-code the autocomplete URL in application.js since the rails url_for isn't available.

Is it possible to make application.js use erb? Am I thinking about this the wrong way?

like image 549
Tom Lehman Avatar asked Apr 07 '09 16:04

Tom Lehman


4 Answers

You could add the url to an attribute on the form or form field, if you don't mind markup that may not pass the validator, and then fetch that attribute with jQuery.

It looks like Rails 3.0 might be going down this route with the javascript helpers using HTML5 custom data attributes: DHH @ Railsconf 09

like image 64
Marc Avatar answered Oct 21 '22 20:10

Marc


Yes, it's possible, on current rails versions just call your file application.js.erb; on older versions you can either roll your own or grab something like this.

like image 41
MarkusQ Avatar answered Oct 21 '22 21:10

MarkusQ


Don't do application.js.erb , that's not a good practice even if caching is involved. Make you autocomplete endpoint (url from which you are getting the data) the same as your form's action url. In your application.js just append &ac=1 to it and make your controllers understand it.

like image 2
skrat Avatar answered Oct 21 '22 21:10

skrat


You don't have to hardcode it-- just create a single JS function that adds the autocomplete listener, and accepts parameters for the autocomplete, and call that JS function from your template:

(code simplified for clarity)

application.js:

function add_autocomplete(id, url) {
   $("#" + id).autocomplete(
      source: url  
   );
};

application_helper.rb:

def add_autocomplete(id, url)
  render :text => "<script> add_autocomplete('#{id}', '#{url}');</script>"
end

ERb template:

<input id="i_want_autocomplete" />
<%= add_autocomplete("i_want_autocomplete", items_js_path() %>
like image 1
joshwa Avatar answered Oct 21 '22 19:10

joshwa