当没有模型时使用Rails jQuery自动完成

时间:2012-02-22 04:52:14

标签: jquery ruby-on-rails-3 autocomplete routes jquery-autocomplete

jQuery自动完成文档声明应该有两个模型,第一个是您要用于自动完成的模型,第二个是具有第一个模型的模型(并附加到您的页面) )。但是,我没有第二个模型,只有一个带有表单元素的Controller w / view,其中一个是第一个Model(Venue)的自动完成输入。

文档说我应该做

resources :parse do
get :autocomplete_venue_name, :on => :collection
end

但由于控制器'Parse'没有模型,因此无效。我尝试制作静态路由,但我需要:收集选项。我该如何解决这个问题?

编辑: 以下是rails + jquery autocomplete插件的代码。请注意,我有一个ProductsController,但我没有Products模型,所以我不能做routes.rb设置:

class Brand<的ActiveRecord :: Base的 端

寻找模型:

   create_table :brand do |t|
     t.column :name, :string
   end

具有所需的AUTOCOMPLETE表格的控制器:

class ProductsController < Admin::BaseController
   autocomplete :brand, :name
end

的routes.rb

resources :products do
   get :autocomplete_brand_name, :on => :collection
end

这种方法只有在我有产品模型时才有效,但我没有。我有一个控制器显示带有自动完成输入的表单。

1 个答案:

答案 0 :(得分:1)

我正在使用jquery multi auto complete插件,您可以在其中选择一个或多个自动

完整的值,如果没有模型,那么它将起作用,例如

$(document).ready(function(){

     var availableTags = [];
    <%@tags.each do |tag|%>
        availableTags.push('<%=tag.name%>');
    <%end%>

    $('#tags').multicomplete({
        source: availableTags
    });

});

在我的情况下@tags = Tag.all

但你可以在控制器动作中给出任何其他值。这个模型不存在

喜欢控制器

@tags = [“可爱”,“美女”,“惊人”]

我用于多次自动填充的代码如下所示。

(function($, $a, $p) { // getting $p as a parameter doesn't require me to "var $p=..." and saves a two bytes ;-) ("var " versus ",x" in argument list [when minifier is shrinking variables])
    $p = $a.prototype;
    $.widget('ui.multicomplete', $a, {
        // Search for everything after the last "," instead of the whole input contents
        _search: function(value) {
            $p._search.call(this, value.match(/\s*([^,]*)\s*$/)[1]);
        },
        // Overwrite _trigger to make custom handling for events while still allowing user callbacks
        // Setting my own callbacks on this.options or binding using .bind() doesn't allow me to properly handle user callbacks, as this must be called AFTER the user callbacks are executed (which isn't possible by bind()ing when this.options[] is set)
        _trigger: function(type, event, data) {
            // call "real" triggers
            var ret = $p._trigger.apply(this, arguments);
            // When its select event, and user callback didn't return FALSE, do my handling and return false
            if (type == 'select' && ret !== false) {
                // When a selection is made, replace everything after the last "," with the selection instead of replacing everything
                var val = this.element.val();
                this.element.val(val.replace(/[^,]+$/, (val.indexOf(',') != -1 ? ' ' : '') + data.item.value + ', '));
                ret = false;
            }
            // Force false when its the focus event - parent should never set the value on focus
            return (type == 'focus' ? false : ret);
        },
        _create:function() {
            var self = this;
            // When menu item is selected and TAB is pressed focus should remain on current element to allow adding more values
            this.element.keydown(function(e) {
                self.menu.active && e.keyCode == $.ui.keyCode.TAB && e.preventDefault();
            });
            $p._create.call(this);
        },
        _initSource: function() {
            // Change the way arrays are handled by making autocomplete think the user sent his own source callback instead of an array
            // The way autocomplete is written doesn't allow me to do it in a prettier way :(
            if ($.isArray(this.options.source)) {
                var array = this.options.source, self = this;
                this.options.source = function(request, response) {
                    response(self.filter(array, request)); // Use our filter() and pass the entire request object so the filter can tell what's currently selected
                };
            }

            // call autocomplete._initSource to create this.source function according to user input
            $p._initSource.call(this);

            // Save a copy of current source() function, than new source() sets request.selected and delegate to original source
            var _source = this.source;
            this.source = function(request, response) {
                request.selected = this.element.val().split(/\s*,\s*/);
                request.selected.pop(); // don't include the term the user is currently writing as selected
                _source(request, response);
            };
            // TODO: instead of overwritting this.source, I can overwrite _search which is easier, but than I'll have to repeat jQuery-UI's code that might change
        },

        // Like $.ui.autocomplete.filter, but excludes items that are already selected
        filter: function(array, request) {
            return $.grep($a.filter(array, request.term), function(value) {
                return $.inArray(value, request.selected) == -1;
            });
        }
    });
})(jQuery, jQuery.ui.autocomplete);

但你应该从jquery.UI.Download文件中包含一些jquery auto complete js文件,并包含在项目中。

jquery.ui.core

jquery.ui.widget

jquery.ui.position

jquery.ui.autocomplete