Rails: How do I autocomplete search for Name but save ID?

activerecord, jquery-ui, ruby, ruby-on-rails, ruby-on-rails-3

Solution

In addition to doing as @LukasSvoboda suggested, you can also override the `select` event callback, which gets triggered when you select an item from the dropdown. In the callback, you can set the text field (which doesn't need to be submitted) to the "label" of the selected item and set the value of a hidden field of the game id (which does need to be submitted) to the "value" of the selected item.

In coffee:

jQuery ->
  $('#play_game_name').autocomplete
    source: $('#play_game_name').data('autocomplete-source')
    select: (event, ui) ->

    # necessary to prevent autocomplete from filling in 
    # with the value instead of the label
    event.preventDefault()

    $(this).val ui.item.label
    $('#game_id').val ui.item.value

In markup:

<%= text_field_tag nil, nil, :id => 'play_game_name', :class => "mlm mtm", data: {autocomplete_source: Game.order(:name).map { |t| { :label => t.name, :value => t.id } } %>
<%= f.hidden_field :game_id, id: 'game_id' %> # tailor to your model

Problem

I've used this video http://railscasts.com/episodes/102-auto-complete-association-revised to set up an autocomplete search input in a form for my app. (The video may be for members only so I'll post my code as well. Essentially it searches a column of the DB (name) and autocompletes in a dropdown as you type. This all works fine however, what I'd like the form to do is submit the ID that correlates to the name, not the name itself. I'm assuming theres no simple way to do this in just the view. Any help would be great. Code below, let me know if any other code would be helpful. Thanks Controller: ``` def game_name game.try(:name) end def game_name=(name) self.game = Game.find_by_name(name) if name.present? end ``` Coffee: ``` jQuery -> $('#play_game_name').autocomplete source: $('#play_game_name').data('autocomplete-source') ``` In the view: ``` <%= f.label :game_name, "Search for a game" %> <%= f.text_field :game_name, :class => "mlm mtm", data: {autocomplete_source: Game.order(:name).map(&:name)} %> ```

Original source

Related problems