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

前端 未结 2 785
难免孤独
难免孤独 2021-02-02 03:26

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 mem

2条回答
  •  你的背包
    2021-02-02 03:53

    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
    

提交回复
热议问题