Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)} %> 
like image 297
Clayton Correia Avatar asked Nov 18 '12 18:11

Clayton Correia


2 Answers

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
like image 83
cdesrosiers Avatar answered Oct 13 '22 16:10

cdesrosiers


By the http://api.jqueryui.com/autocomplete/#option-source you can set data to the autocomplete.

You need to change the text_field line like:

<%= f.text_field :game_name, :class => "mlm mtm", data: {autocomplete_source: Game.order(:name).map { |t| { :label => t.name, :value => t.id } } %>

For more advanced features consider to use select2 or chosen.

like image 43
Lukas Svoboda Avatar answered Oct 13 '22 18:10

Lukas Svoboda