轨,多条件搜索(如果值不为空) [英] Rails searching with multiple conditions (if values are not empty)

查看:111
本文介绍了轨,多条件搜索(如果值不为空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个模型图书与现场 word_count中,其中包括潜在的许多其他类似的领域。

Let's say I have a model Book with a field word_count, amongst potentially many other similar fields.

有什么好的办法,我串起来的条件在数据库中的高级搜索?在上面的例子中,我必须和箱子一个搜索形式之间的字数___ ___和。如果用户填写第一个框,然后我要回与字的所有书籍数大于该值;同样,如果用户填写了第二个框,然后我要回与字的所有书籍计数低于该值。如果这两个值填写,那么我想在该范围内返回字数。

What is a good way for me to string together conditions in an "advanced search" of the database? In the above example, I'd have a search form with boxes for "word count between ___ and ___". If a user fills in the first box, then I want to return all books with word count greater than that value; likewise, if the user fills in the second box, then I want to return all books with word count less than that value. If both values are filled in, then I want to return word counts within that range.

显然,如果我这样做

Book.where(:word_count => <first value>..<second value>)

那么,如果只是其中一个字段中填入这将打破。有没有什么办法可以很好地处理这个问题?请记住,可能有许多类似的搜索条件,所以我不希望建立单独的查询每一个可能的组合。

then this will break if only one of the fields was filled in. Is there any way to handle this problem elegantly? Keep in mind that there may be many similar search conditions, so I don't want to build separate queries for every possible combination.

很抱歉,如果这个问题已经被问过,但搜索网站还没有产生任何有用的结果呢。

Sorry if this question has been asked before, but searching the site hasn't yielded any useful results yet.

推荐答案

有关我们先进的搜索,我们创建一个封装ActiveRecord的查询成简单的方法过滤器对象。它最初是在此基础上 Thoughtbot帖子

For our advanced searching we create a filter object which encapsulates the activerecord queries into simple methods. It was originally based on this Thoughtbot post

这本书过滤器可以是这个样子:

A book filter could look something like this:

class BookFilter
  def initialize
    @relation = Book.scoped
  end

  def restrict(r)
    minimum_word_count!(r[:first]) if r[:first].present?
    maximum_word_count!(r[:second]) if r[:second].present?
    recent! if r.try(:[], :recent) == '1'
    @relation
  end

  protected

  def recent!
    where('created_at > ? ', 1.week.ago)
  end

  def minimum_word_count!(count)
    where('word_count >= ? ', count)
  end

  def maximum_word_count!(count)
    where('word_count <= ?', count)
  end

  def where(*a)
    @relation = @relation.where(*a)
  end
end

#to use
books = BookFilter.new.restrict(params)

这篇关于轨,多条件搜索(如果值不为空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆