Rails jQuery-客户端自动完成

Rails jQuery-autocomplete client-side

需要使用自动完成字段而不是下拉字段来更新我的食谱#new 视图。在阅读了一些文章后,我决定使用 jQuery-ui。

所以在 Gemfile 中添加

gem "jquery-ui-rails"

和application.js

//= require jquery-ui

景色

<%= form_for @recipe do |f| %>
  <%= f.fields_for :quantities do |quantity| %>
    <%= f.label :ingredient, "Ingredient" %>
    <%= f.text_field :ingredient_id, 
                      class: "search-query", 
                      type: "search", 
                      data: { autocomplete_source:
                                    Ingredient.order(:name).map { |t| 
                                      { :label => t.name, :value => t.id } }%>  
  <% end %>
<% end %>

RecipesController 需要成分 ID,但表单提交:

"ingredient_id"=>"Sugar"

Started POST "/recipes" for 127.0.0.1 at 2015-11-22 20:35:48 +0100
Processing by RecipesController#create as HTML
  Parameters: {"utf8"=>"V",
    "authenticity_token"=>"7EOoZpjm3hW3Bzv4N6lLWu534xw==", 
    "recipe"=>{"name"=>"Apple Pie", 
    "quantities_attributes"=>
      {"1448220899039"=>
      {"ingredient_id"=>"Sugar", 
       "scale_id"=>"2", 
       "amount"=>"100"}}, 
    "caption"=>"Grandmother's Apple Pie"},
    "button"=>""}

我如何处理自动完成,它提交的是成分 ID 而不是名称?

我在我的观点中添加了这个:

<%= text_field_tag nil, nil, :class => 'searchbar', data: { autocomplete_source: Ingredient.order(:name).map { |t| 
                                                      { :label => t.name, :value => t.id } } } %>

<%= f.hidden_field :ingredient_id, class: 'ingredient_id' %>

<script>
  $('.searchbar').autocomplete({
    source: $('.searchbar').data('autocomplete-source'),
    select: function(event, ui) {
      event.preventDefault();
      this.value = ui.item.label
      $('.ingredient_id').val(ui.item.value)
    }
 });
</script>