【问题标题】:How to redirect autocomplete search box to show view如何重定向自动完成搜索框以显示视图
【发布时间】:2016-05-07 12:55:39
【问题描述】:

我是 Rails 新手,非常感谢您的意见。我创建了一个带有自动完成搜索框的应用程序。当用户键入疾病时,我希望他被重定向到“显示”视图,其中包含有关该疾病的一些信息。自动完成工作正常,但没有重定向。

这是我的完整代码 https://gist.github.com/ollac21/0ab136d46d06e37fb2c2

我的路线

Rails.application.routes.draw do

resources :diseases do
  get :search, :on => :collection
end


root 'diseases#index'
end

我的控制器

class DiseasesController < ApplicationController

before_action :set_disease, only: [:show, :edit, :update, :destroy]


def index
  respond_to do |format|
    format.html
    format.json { @diseases = Disease.search(params[:term]) }
  end
end


def show
end

private
# Use callbacks to share common setup or constraints between actions.
def set_disease
  @disease = Disease.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def disease_params
  params.require(:disease).permit(:name)
end

end

我的看法

<h1> Type any disease to find info about it </h1>

<div class="diseases-search">
<input type="text" id="diseases-search-txt" autofocus>
<div class="results" id="diseases-search-results"></div>
</div>


<script>
$(function() {
new app.Diseases;
});
</script>

我的 Javascript

    app.Diseases = function() {
  this._input = $('#diseases-search-txt');
  this._initAutocomplete();
};

app.Diseases.prototype = {
  _initAutocomplete: function() {
    this._input
      .autocomplete({
        source: '/diseases',
        appendTo: '#diseases-search-results',
        select: $.proxy(this._select, this)
      })
      .autocomplete('instance')._renderItem = $.proxy(this._render, this);
  },

  _render: function(ul, item) {
    var markup = [

      '<span class="name">' + item.name + '</span>'

    ];
    return $('<li>')
      .append(markup.join(''))
      .appendTo(ul);
  },

  _select: function(e, ui) {
    this._input.val(ui.item.name);
    return false;
  }
};

另外,我用它来“激励自己” https://github.com/lugolabs/tutorials/tree/master/amazing

非常感谢一些帮助 谢谢!

【问题讨论】:

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


    【解决方案1】:

    您可以为控制器中的每个desease(或json view)生成路由并将其添加到json 响应中。然后将链接添加到您的标记中:

    _render: function(ul, item) {
      var markup = [
        // Assuming that item is the disease record
        '<a href='+ item.the_url +'><span class="name">' + item.name + '</span></a>'
    
      ];
    return $('<li>')
      .append(markup.join(''))
      .appendTo(ul);
    },
    

    【讨论】:

    • 谢谢。我接受了你的想法。我在控制器中为每种疾病添加了一条路线,并将其添加到 json 响应中。不过,我没有更改标记,而是更改了自动完成小部件中的“选择”选项,以将结果重定向到显示视图。通过更改标记,只有单词被重定向到视图。选择:函数(e,ui){ window.location.href = ui.item.the_url; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2013-08-20
    • 2015-03-31
    • 2012-11-21
    • 2017-07-18
    • 2018-02-04
    相关资源
    最近更新 更多