我是 Rails 新手,非常感谢您的意见。我创建了一个带有自动完成搜索框的应用程序。当用户输入一种疾病时,我希望他被重定向到“显示” View ,其中包含有关这种疾病的一些信息。自动完成工作正常,但没有重定向。
这是我的完整代码 https://gist.github.com/ollac21/0ab136d46d06e37fb2c2
我的路线
Rails.application.routes.draw do
resources :diseases do
get :search, :on => :collection
end
root 'diseases#index'
end
我的 Controller
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
我真的很感激一些帮助 谢谢!
最佳答案
您可以在 Controller (或 json View
)中为每个 disease
生成路由,并将其添加到 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);
},
关于javascript - 如何重定向自动完成搜索框以显示 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35090457/