Multi-field searches in Rails
I want to do an advanced search form in Rails that has these abilities:
Required
- 5
field_tag
s where a user can input a search term that searches a开发者_StackOverflow specific field in the table. - 1
field_tag
that searches all fields in the table (DONE).
Preferable
- Be able to specify operators like
AND
,OR
, etc. on these searches. - Be able to specify more detailed operators like SO does with
this
,inquestion
, etc.
How can I make this happen in practice, especially the 1st bullet point?
I haven't tested this, someone please edit the syntax accordingly, but logically I do not see why it wouldn't work.
app/views/posts/_form.html.erb
<% form_tag(@post, :method => :get) do %>
<p>
Search Phrase
<%= text_field_tag :phrase, params[:phrase] %>
</p>
<p>
<%= radio_button_tag :search_everything, true %>
Search Everything
</p>
<p>
<%= radio_button_tag :search_everything, false %>
Advanced Search
</p>
<div id="advacned_search">
<% format_column_names(Post.column_names) do |cn| %>
<%= check_box_tag "post[column_names][]", cn %> Field
<%= check_box_tag cn %><br/>
<% end %>
</div>
<p>
<%= submit_tag "Search" %>
</p>
<% end %>
app/helpers/post_helper.rb
def format_column_names(cns)
filtered_names = "id" #add the other column names you do not want
cns.delete_if {|cn| filtered_names.include?(cn) }
return cns
end
app/controllers/posts_controller.rb
def index
phrase = params[:phrase]
if params[:search_everything]
@posts = Post.find(:all, :conditions => everything_conditions(phrase))
else
column_names = params[:column_names]
@posts = Post.find(:all, :conditions => specific_conditions(column_names, phrase))
end
end
def everything_conditions(phrase)
[Post.column_names.map {|cn| "#{cn}=?" }, phrase]
end
def specific_conditions(phrase, column_names)
[column_names.map {|cn| "#{cn}=?" }.join("or "), phrase]
end
public/javascripts/post.js
#make sure you include jQuery and this file into your view`
jQuery.noConflict();
jQuery(document).ready(function() {
$("input[name$='search_everything']").click(function(){
var value = $(this).val();
if(value) {
$("#advanced_search").hide();
} else {
$("#advanced_search").show();
}
}
})
精彩评论