我想在Rails中使用具有以下功能的高级搜索表单:
必需
field_tag
s,用户可以在其中输入搜索表格中特定字段的搜索字词。field_tag
搜索表格中的所有字段(DONE)。优选的的
AND
,OR
等运营商。this
,inquestion
等那样指定更详细的运算符。如何在实践中实现这一点,尤其是第一个要点?
答案 0 :(得分:1)
我没有对此进行测试,有人请相应地编辑语法,但从逻辑上讲,我不明白为什么它不起作用。
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
#确保将jQuery和此文件包含在您的视图中
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();
}
}
})