代码之家  ›  专栏  ›  技术社区  ›  GSP

在搜索Rails方式中可选的过滤器参数组合

  •  1
  • GSP  · 技术社区  · 16 年前

    我有一个简单的列表页面,它有几个搜索过滤器状态,这是一个简单的枚举和一个测试查询,我想将其与我的模型的标题和描述字段进行比较。

    在我的控制器中,我想执行如下操作:

    def index
      conditions = {}
      conditions[:status] = params[:status] if params[:status] and !params[:status].empty?
      conditions[???] = ["(descr = ? or title = ?)", params[:q], params[:q]] if params[:q] and !params[:q].empty?
      @items = Item.find(:all, :conditions => conditions)
    end
    

    不幸的是,看起来我不能混合这两种类型的条件(散列和参数化版本)。有没有一种“轨道方式”可以做到这一点,或者我只需要做一些像这样糟糕的事情:

    has_status = params[:status] and !params[:status].empty?
    has_text = params[:q] and !params[:q].empty?
    if has_status and !has_text
       # build paramatized condition with just the status
    elsif has_text and !has_status
       # build paramatized condition with just the text query
    elsif has_text and has_status
       # build paramatized condition with both
    else
       # build paramatized condition with neither
    end
    

    我要从休眠状态和标准迁移,所以如果我没有正确地考虑这一点,请原谅我…

    环境:Rails 2.3.4

    3 回复  |  直到 16 年前
        1
  •  2
  •   Tatjana N.    16 年前

    可以使用作用域混合哈希和数组条件:

    hash_conditions = {}
    # build hash_conditions
    
    items_scope = Item.scoped(:conditions => hash_conditions)
    
    unless params[:q].blank?
      items_scope = items_scope.scoped(:conditions => ["(descr = ? or title = ?)", params[:q], params[:q]])
    end
    
    ...
    
    items = items_scope.all
    

    因此,您可以混合和匹配任何类型的条件,并且只有在这样做时才会执行查询。 items_scope.all

        2
  •  0
  •   zed_0xff    16 年前
    a=[],b=[]
    unless params[:status].blank?
      a << "status = ?"
      b << params[:status]
    end
    unless params[:q].blank?
      a << "(descr = ? or title = ?)"
      b << params[:q] << params[:q]
    end
    @items = Item.all( :conditions => [a.join(" AND "), b] )
    
        3
  •  0
  •   GSP    16 年前

    对我来说,更好的搜索找到了一个叫做“命名范围”的东西,它看起来正是我要找的。我将要看看它是否能与遗嘱宝石一起工作……

    参考文献: http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/