为简单的搜索Rails 3构建静态下拉菜单 [英] Build static dropdown menu for simple search Rails 3
问题描述
我在Rails应用程序中进行了简单的搜索,但是它仅搜索表的单个列.我正在尝试添加一个简单的下拉菜单,其中包含"last_name"和"city"之类的选项,以便用户可以选择要搜索的列.
I have a simple search working in my rails app, but it only searches a single column of my table. I'm trying to add a simple dropdown menu with options like "last_name" and "city" so the user can select the column to search.
我认为我有:
<%= form_tag teachers_path, :method => 'get', :id => "teachers_search" do %>
<%= hidden_field_tag :direction, params[:direction]%>
<%= hidden_field_tag :sort, params[:sort]%>
<p>
<%= text_field_tag :search, params[:search], placeholder: 'First Name' %>
<%= submit_tag "Search", :first_name => nil %>
</p>
<% end %>
在我的模型中:
def self.search(search)
if search
where('first_name LIKE ?', "%#{search}%")
else
scoped
end
end
任何帮助都将不胜感激.
Any help greatly appreciated.
推荐答案
您可以为下拉菜单添加一个select_tag
You can add a select_tag for your drop down menu
<%= select_tag "search_from", "<option>first_name</option><option>last_name</option><option>city_name</option>".html_safe%>
在控制器中,您可以将params [:search_from]中的值传递给搜索方法.并对其进行修改以包含列名称
In your controller you can pass the value in params[:search_from] to your search method. and modify it to include the column name
def self.search(search, column_name)
if search
where('? LIKE ?', column_name, "%#{search}%")
else
scoped
end
end
我已经用粗略的方式编写了它,但我希望它能传达出信息.
I've written it in a crude way but i hope it gets the message along.
这篇关于为简单的搜索Rails 3构建静态下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!