Rails: how to autocomplete name lookup but save id?

I used this video http://railscasts.com/episodes/102-auto-complete-association-revised to configure the form's autocomplete input for my application. (The video can only be for participants, so I will also publish my code. In fact, it looks for the DB column (name) and autocompletes in the drop-down list as it is input. This all works fine, but I would like form to do to represent an identifier that correlates with the name, not with the name itself.

I assume that there is no easy way to do this in a view only. Any help would be great. The 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 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)} %> 
+8
ruby jquery-ui ruby-on-rails activerecord ruby-on-rails-3
source share
2 answers

In addition to using @LukasSvoboda, you can also override the select event callback that starts when an item is selected from the drop-down list. In the callback, you can set the text box (which does not have to be sent) to the β€œlabel” of the selected item and set the value to hidden fields of the game identifier (which must be sent) to the "value" of the selected element.

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 the 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 
+9
source share

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

You need to change the text_field line as follows:

 <%= 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 functions, it is recommended to use select2 or selected.

+3
source share

All Articles