【问题标题】:Rails jQuery-autocomplete client-sideRails jQuery-自动完成客户端
【发布时间】:2016-02-24 21:41:01
【问题描述】:

需要使用自动完成字段而不是下拉字段更新我的 recipe#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"=>"糖"

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 而不是名称?

【问题讨论】:

    标签: jquery ruby-on-rails autocomplete jquery-ui-autocomplete


    【解决方案1】:

    我在视图中添加了这个:

    <%= 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-14
      • 2012-03-20
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      • 1970-01-01
      相关资源
      最近更新 更多