【问题标题】:Ruby on Rails: Cant figure out why my jQuery-ui autocomplete isn't working?Ruby on Rails:无法弄清楚为什么我的 jQuery-ui 自动完成功能不起作用?
【发布时间】:2017-01-18 08:06:12
【问题描述】:

我刚刚按照 youtube 教程向我的搜索字段添加 jQuery-ui 自动完成功能。这是教程的链接:https://www.youtube.com/watch?v=iMz8HmrQ350

由于某种原因,它无法正常工作,尽管阅读了教程并不断地重新检查语法。当我重新加载网络浏览器时,我没有收到任何错误,但是,当我在搜索字段中键入时,没有任何内容显示为下拉菜单。有趣的是,如果我将数组用于示例数据,它会起作用(下拉菜单会出现使用示例数组数据的建议)。但是当我尝试将它链接到我的帖子数据库时,它不再起作用。我在下面展示了两种方式的示例代码。

我的代码如下 - 非常感谢任何帮助我一直在尝试添加此功能一段时间尝试无数的教程和方法。越来越烦了哈哈。

我是编码新手,到目前为止我已经自学了。如果需要任何其他文件,请告诉我。

附言。我目前正在使用弹性搜索和搜索踢进行简单搜索。这可能与自动完成功能不起作用有关吗?我还在我的 gem 文件中使用 gem: "gem 'query-ui-rails'" 以防万一,这很重要。

posts.coffee

jQuery ->
$('#search').autocomplete
    source: "/search_suggestions"

search_suggestions_controller.rb

class SearchSuggestionsController < ApplicationController

    def index
        render json: SearchSuggestion.terms_for(params[:term])
    end
end

如果我使用数组作为样本数据,它可以工作 - 示例:

 class SearchSuggestionsController < ApplicationController

     def index
        render json: %w[test test1]
     end
 end

模型:search_suggestion.rb

class SearchSuggestion < ApplicationRecord

    attr_accessible :popularity, :term

    def self.terms_for(prefix)
        suggestions = where("term like ?", "#{prefix}_%")
        suggestions.order("popularity desc").limit(10).pluck(:term)
    end

    def self.index_posts
        Post.find_each do |post|
            index_term(post.title)
            post.title.split.each { |t| index_term(t) }
        end
    end

    def self.index_term(term)
        where(term: term.downcase).first_or_initialize.tap do |suggestion|
            suggestion.increment! :popularity
        end
    end
end

任务文件:search_suggestions.rake

 namespace :search_suggestions do 
     desc "Generate search suggestions from posts"
     task :index => :environment do
         SearchSuggestion.index_posts
     end
end

【问题讨论】:

  • 有人吗???拜托

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


【解决方案1】:

如果它适用于您的数组存根,那么这意味着您的 JS 可能正在运行,并且您的控制器/模型中发生了一些奇怪的事情。

您是否检查过 jquery 对您的浏览器发出的请求?和回应?

我不确定您的数据是如何构成的,但是

suggestions = where("term like ?", "#{prefix}_%")

看起来有点可疑。

需要检查的几点:

  1. 在浏览器中检查来自开发者控制台的请求。检查术语参数是否正确发送,以及响应负载中是否有任何内容(您描述的方式看起来响应为空)

  2. 在你的控制器/模型中使用pry,检查传入的参数,查询结果suggestions = where("term like ?", "#{prefix}_%")

  3. 检查 rake 任务是否确实有效(您运行了 rake 任务对吗?)。如果您的条款已正确填写。 (在控制台中类似于 SearchSuggestion.all。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2014-12-08
    • 2012-05-16
    相关资源
    最近更新 更多