【问题标题】:Multi-field searches in RailsRails 中的多字段搜索
【发布时间】:2011-09-17 23:38:30
【问题描述】:

我想在 Rails 中创建一个具有以下功能的高级搜索表单:

必填

  • 5 field_tags 用户可以在其中输入搜索词以搜索表格中的特定字段。
  • 1 field_tag 搜索表中的所有字段 (DONE)。

首选

  • 能够在这些搜索中指定AND、OR 等运算符。
  • 能够指定更详细的运算符,如 SO 对 this、inquestion 等所做的。

如何在实践中实现这一点,尤其是第一个要点?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 search


    【解决方案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();
            }
         }
    
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-13
      • 2012-07-19
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      相关资源
      最近更新 更多