我是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
我真的很感激一些帮助 谢谢!
答案 0 :(得分:0)
您可以为控制器中的每个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);
},