2

Нужно обновить мой новый рецепт # new с полем автозаполнения вместо выпадающего поля. После прочтения некоторых статей я решил использовать jQuery-ui.Rails jQuery-autocomplete на стороне клиента

Так добавили в 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 ожидает идентификатор ингредиента, но форма совершает:

«ingredient_id» => «Сахар»

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 вместо имени?

ответ

0

Я добавил это, на мой взгляд:

<%= 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> 
Смежные вопросы