在我的Rails 4应用程序中,我使用jQuery的自动完成功能在导航栏中有一个搜索框。我在用户的索引操作上使用它。一切都很好,除非他们从下拉列表中点击用户的名字,我希望它转到他们的个人资料页面。
用户控制器:
def index
if params[:term]
@users = User.order(:name).where("LOWER(name) like ?", "%#{params[:term]}%")
render json: @users.map(&:name)
end
if params[:users_name]
@users = User.search(params[:users_name])
end
end
搜索栏:
<%= form_tag users_path, :method => 'get', :role => 'search', :class => "navbar-form navbar-right" do %>
<div class="form-group has-feedback">
<%= autocomplete_field_tag :users_name, '', users_path, :placeholder => "Search", :required => true, :class => "form-control transition" %><span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
<% end %>
我的用户路由是基本的,只有
resources :users
用户/ index.html.erb:
<div class="row">
<div class="span12">
<% if @users %>
<ol class="list-inline">
<%= render @users %>
</ol>
<% end %>
</div>
</div>
_user.rb:
I have the appropriate file with what I want displayed here as well.
就像我提到的,自动完成工作正常,当我开始输入名称时,用户名将下拉。我遇到的问题是,如果他们开始输入justin并且“justin timberlake”是其中一个下拉菜单,他们点击Justin Timberlake我希望它转到他的个人资料页面profile_page(@user)
答案 0 :(得分:0)
我确信实现这一目标的方法很少,但一个简单的解决方案就是这样做......
users_controller.rb
def index
if params[:term]
@users = User.order(:name).where("LOWER(name) like ?", "%#{params[:term]}%")
payload = []
# build up data set
@users.each do |u|
payload.push({label: u.name, value: u.id})
end
render json: @users.map(&:name)
elsif params[:users_name]
@users = User.search(params[:users_name])
end
end
在你的JS代码中
$("#element_name").autocomplete({
source: "/user",
...
select: function (e, d) {
// redirect to the user profile page..
window.location = "/users/" + d.item.value;
}