【问题标题】:How to chain optional Mongoid criteria in separate statements?如何在单独的语句中链接可选的 Mongoid 标准?
【发布时间】:2011-03-17 03:02:45
【问题描述】:

我正在尝试根据可选的导轨链接标准 参数。

我希望能够同时根据所选标签进行过滤 以及搜索。

这是适用于所有情况的当前代码:

if params[:tag] and params[:search] 
  @notes = Note.tagged_with_criteria(params[:tag]).full_text_search(params[:search]) 
elsif params[:tag] 
  @notes = Note.tagged_with_criteria(params[:tag]) 
elsif params[:search] 
  @notes = Note.full_text_search(params[:search]) 
end 

我尝试简单地使用

  @notes = Note.tagged_with_criteria(params[:tag]).full_text_search(params[:search]) 

没有 if 语句,但是如果只有一个参数是 给定,则返回所有音符。

每种方法(tagged_with_criteria 和 full_text_search)都是 如果参数为 nil / 为空,则返回 Note.criteria。

有没有更简单、更优雅的方式来像这样链接 Mongoid 标准?

我宁愿继续逐一跟踪标准,而不是不得不做 奇怪的“if params[...] and params[...]”的事情..

更新:以下是当前的方法:

def tagged_with_criteria(_tags)
  _tags = [_tags] unless _tags.is_a? Array
  if _tags.empty?
    criteria
  else
    criteria.in(:tags => _tags)
  end
end


  def self.full_text_search(query)
    if query
      begin
        regex = /#{query}/
        # supplied string is valid regex (without the forward slashes) - use it as such
        criteria.where(:content => regex)
      rescue
        # not a valid regexp -treat as literal search string
        criteria.where(:content => (/#{Regexp.escape(query)}/))
      end
    else
      # show all notes if there's no search parameter
      criteria
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid


    【解决方案1】:

    在这种情况下,我会修改范围以在传入空白值时不执行任何操作。

    我认为可能发生的情况是您从 params 哈希中获取了空字符串,这导致您的代码认为输入了某些内容。尝试使用这些编辑的范围。

    def tagged_with_criteria(_tags)
      _tags = Array.wrap(_tags).reject(&:blank?)
      if _tags.empty?
        criteria
      else
        criteria.in(:tags => _tags)
      end
    end
    
    def self.full_text_search(query)
      if query.present?
        begin
          regex = /#{query}/
          # supplied string is valid regex (without the forward slashes) - use it as such
          criteria.where(:content => regex)
        rescue
          # not a valid regexp -treat as literal search string
          criteria.where(:content => (/#{Regexp.escape(query)}/))
        end
      else
        # show all notes if there's no search parameter
        criteria
      end
    end
    

    【讨论】:

    • 什么都不做是指返回零?
    • 这正是我们在 CloudMailin 中使用 Mongoid 时采用的方法。如果参数为空,您也可以通过传递 {} 来对老式作用域执行类似的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 2018-01-02
    相关资源
    最近更新 更多