I want to have a text box that the user can type in that shows an Ajax-populated list of my model’s names, and then when the user selects one I want the HTML to save the model’s ID, and use that when the form is submitted.
I’ve been poking at the auto_complete plugin that got excised in Rails 2, but it seems to have no inkling that this might be useful. There’s a Railscast episode that covers using that plugin, but it doesn’t touch on this topic. The comments point out that it could be an issue, and point to model_auto_completer as a possible solution, which seems to work if the viewed items are simple strings, but the inserted text includes lots of junk spaces if (as I would like to do) you include a picture into the list items, despite what the documentation says.
I could probably hack model_auto_completer into shape, and I may still end up doing so, but I am eager to find out if there are better options out there.
I’ve got a hackneyed fix for the junk spaces from the image. I added a
:after_update_element => 'trimSelectedItem'to the options hash of themodel_auto_completer(that’s the first hash of the three given). MytrimSelectedItemthen finds the appropriate sub-element and uses the contents of that for the element value:However, this then runs afoul of the
:allow_free_textoption, which by default changes the text back as soon as the text box loses focus if the text inside is not a ‘valid’ item from the list. So I had to turn that off, too, by passing:allow_free_text => trueinto the options hash (again, the first hash). I’d really rather it remained on, though.So my current call to create the autocompleter is:
And the products/index.js.erb is: