【问题标题】:How to connect jQuery autocomplete widget to a model?如何将 jQuery 自动完成小部件连接到模型?
【发布时间】:2025-12-29 17:00:11
【问题描述】:

我在表单中使用 jQuery 自动完成小部件(我在此处找到:http://jqueryui.com/autocomplete/#multiple)来创建新的“事物”。输入预定的标签以进行选择效果很好,但我不知道如何让小部件从我的“类别”模型的实例中进行选择。换句话说,我想将每个新事物与几个类别相关联。我应该改变什么?

Things 和 Categories has_many of each other:通过中介模型“CategoryThing”。我正在使用 Rails 4.0.10。

事物/new.html.erb:

<h1>Add Something!</h1>
<p>
  <%= form_for @thing, :url => things_path, :html => { :multipart => true } do |f| %>

    <%= f.text_field :name, :placeholder => "Name of the thing" %>
    <br>

    <head>
      <meta charset="utf-8">
      <title>jQuery UI Autocomplete - Multiple values</title>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
      <script src="//code.jquery.com/jquery-1.10.2.js"></script>
      <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
      <link rel="stylesheet" href="/resources/demos/style.css">
      <script>
      $(function() {
        var availableTags = [
          <%= Category.pluck(:name).map { |name| "\"#{name}\"" }.join(",\n") %>
        ];
        function split( val ) {
          return val.split( /,\s*/ );
        }
        function extractLast( term ) {
          return split( term ).pop();
        }

        $( "#tags" )
          // don't navigate away from the field on tab when selecting an item
          .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
            }
          })
          .autocomplete({
            minLength: 0,
            source: function( request, response ) {
              // delegate back to autocomplete, but extract the last term
              response( $.ui.autocomplete.filter(
                availableTags, extractLast( request.term ) ) );
            },
            focus: function() {
              // prevent value inserted on focus
              return false;
            },
            select: function( event, ui ) {
              var terms = split( this.value );
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push( ui.item.value );
              // add placeholder to get the comma-and-space at the end
              terms.push( "" );
              this.value = terms.join( ", " );
              return false;
            }
          });
      });
      </script>
    </head>
    <body>

    <div class="ui-widget">
      <label for="tags">Categories: </label>
      <input id="tags" size="50">
    </div>

    <%= f.label :related_things %>
    <%= f.collection_select :related_things, Thing.all, :id, :name %>
    <br>
    <%= f.label :display_picture %>
    <%= f.file_field :avatar %>
    <br>
    <%= f.submit "Submit", class: "btn btn-primary" %>
  <% end %>
</p>

事物/控制器:

class ThingsController < ApplicationController

  def show
    @thing = Thing.find(params[:id])
    @category_things = CategoryThing.all
    @thing.categories.build
  end

  def new
    @thing = Thing.new
    @things = Thing.all
  end

  def create
    @thing = Thing.new(thing_params)
    if @thing.save
      redirect_to @thing
    else
      render 'new'
    end
  end

  private

    def thing_params
      params.require(:thing).permit(:name, :image_path, :avatar, category_ids: [])
    end

end

【问题讨论】:

    标签: jquery ruby-on-rails forms model jquery-autocomplete


    【解决方案1】:

    你应该试试 gem selected-rails。这里是gemhttps://github.com/tsechingho/chosen-rails的教程,不过总结一下:

    1) 将 gem 添加到您的 gemfile 中

    gem "chosen-rails"
    

    2) 添加适当的资源(js 和 css) 在 application.js

    //= require chosen-jquery
    

    application.css.csss

     *= require chosen
    

    3) 将类 chosen-select 添加到您的字段中。例如:

    <%= f.collection_select :product_id , Product.all, :id, :name, {prompt: "Seleccione un producto"}, {class: "chosen-select"} %>
    

    4) 将这一行添加到控制器的咖啡脚本代码中,在我的例子中是 order_lines.js.coffee

    jQuery ->
    

    $('.chosen-select').chosen()

    【讨论】:

    • 多选是否可用?我在自述文件中找不到任何内容。
    最近更新 更多