轻松自动完成搜索的“所有结果”选项Ruby on Rails

时间:2018-11-30 22:45:30

标签: jquery ruby-on-rails ruby-on-rails-5

我正在尝试将“所有结果”选项添加到下拉搜索中。我将搜索限制为5条记录:

# search_controller.rb
def search
  @catalogs = Catalog.ransack(name_cont: params[:q]).result(distinct: true)
  @products = Product.ransack(name_cont: params[:q]).result(distinct: true)

  respond_to do |format|
    format.html {}
    format.json {
      @catalogs = @catalogs.limit(5)
      @products = @products.limit(5)
    }
  end
end

现在,如果结果超过5个,我想添加一个额外的选项(无论是目录还是产品,在所有结果之上只是一个额外的选项)。这是我的easy-autocomplete设置:

document.addEventListener("DOMContentLoaded", function() {
  $input = $("[data-behavior='autocomplete']");

  var options = {
    getValue: "name",
    url: function(phrase) {
      return "/search.json?q=" + phrase;
    },
    categories: [
      { listLocation: "catalogs", header: "<strong>Catalogs</strong>" },
      { listLocation: "products", header: "<strong>Products</strong>" }
    ],
    list: {
      onChooseEvent: function() {
        var url = $input.getSelectedItemData().url;
        console.log(url);
        $input.val("");
        window.location.href = url;
      }
    }
  };

  $input.easyAutocomplete(options);
});

我尝试用Google搜索,因为它看起来非常明显,但是我什么都没找到。阅读所有easy-autocomplete文档,但仍然存在此问题。谢谢您的帮助和时间!

更新

再次阅读easy-autocomplete文档,并在onLoadEvent下找到Events。简化的解决方案:

document.addEventListener("DOMContentLoaded", function() {
  // code ...
      onLoadEvent: function() {
        $('.easy-autocomplete-container ul').append("<li>Show all</li>");
      }
  // code ...
  };

  $input.easyAutocomplete(options);
});

0 个答案:

没有答案