Rails:为数据库列编写搜索功能

时间:2016-06-05 18:51:10

标签: ruby-on-rails ruby search

我必须为我的Rails应用程序编写搜索功能。我在数据库中有多列,用户可能希望根据数据库中的列的任意组合进行搜索。我现在实施的方式变得越来越难看。所以我猜这可能有宝石,或者可能有更好的方法来解决这个问题。下面是我的代码片段。

class Finance < ActiveRecord::Base

  CASH_FLOW = ['Income', 'Expense']
  PAID_BY   = ['Person A', 'Person B']

  validates :amount,    presence: true
  validates :cash_flow, presence: true, inclusion: { in: CASH_FLOW }
  validates :date,      presence: true
  validates :paid_by,   inclusion: { in: PAID_BY }, if: "cash_flow == 'Expense'"
  validates :paid_by,   presence: true, if: "cash_flow == 'Expense'"

  def self.search(id, amount, amount_dropdown, cash_flow, start_date, finish_date, description, paid_by)
    if id.present? && amount.empty? && cash_flow.empty? && start_date.empty? && finish_date.empty? && description.empty? && paid_by.empty?
      Finance.find_by_id(id)
    elsif id.empty? && amount.present? && cash_flow.empty? && start_date.empty? && finish_date.empty? && description.empty? && paid_by.empty?
      Finance.where("amount #{amount_dropdown} ?", amount)
   elsif id.empty? && amount.empty? && cash_flow.present? && start_date.empty? && finish_date.empty? && description.empty? && paid_by.empty?
      Finance.where('cash_flow = ?', cash_flow)
   elsif id.empty? && amount.empty? && cash_flow.empty? && start_date.present? && finish_date.empty? && description.empty? && paid_by.empty?
      Finance.where('date = ?', Date.parse(start_date))
   elsif id.empty? && amount.empty? && cash_flow.empty? && start_date.empty? && finish_date.present? && description.empty? && paid_by.empty?
      Finance.where('date = ?', Date.parse(finish_date))
   elsif id.empty? && amount.empty? && cash_flow.empty? && start_date.present? && finish_date.present? && description.empty? && paid_by.empty?
      Finance.where('date >=  ? and date <= ?', Date.parse(start_date), Date.parse(finish_date))
   elsif id.empty? && amount.empty? && cash_flow.empty? && start_date.empty? && finish_date.empty? && description.present? && paid_by.empty?
      Finance.where('description like ?', "%#{description}%")
   elsif id.empty? && amount.empty? && cash_flow.empty? && start_date.empty? && finish_date.empty? && description.empty? && paid_by.present?
      Finance.where('paid_by = ?', paid_by)
   end
 end

end

目前我正在检查哪些字段为空以及哪些字段存在,并且基于我正在编写搜索查询。请让我知道如何做得更好。我必须为几乎所有模型实现搜索功能。

1 个答案:

答案 0 :(得分:0)

我不确定这是个好主意,特别是如果你有很多模型需要搜索。有一些非常可靠的解决方案,开箱即用,比您的解决方案更好。

例如,您可以使用searchkick。它很容易实现,并具有很多功能。在你的情况下,它将是这样的:

def Finance
  searchkick

  self.search(....)
    Finance.reindex
    Finance.search ... 
  end
end

查看他们的github,了解如何自定义搜索。