【问题标题】:Compose SQL Queries编写 SQL 查询
【发布时间】:2016-12-21 18:03:13
【问题描述】:

我正在尝试在 Rails5 应用程序上实现一个简单的搜索引擎。

基本上,我在一个表单中有几个字段,我需要获取与所有输入值匹配的所有记录。请注意,所有值都是可选的。

我可以搜索的值为name、description、created_at。

我的想法是为每个值创建一个子句,然后将它们连接在一起。

class EmployeeSearch < ApplicationRecord
  self.table_name = 'employees'


  def results
    # MAGIC HAPPENS HERE
  end

 private

 def table
  Employee.arel_table
 end

 def name_condition 
  table[:name].eq(name)
 end

def description_condition
  table[:description].matches("%#{description}%") unless description.blank?
 end

def created_at_condition
 ...
end

end

EmployeeSearch.new(name: 'John Doe', created_at: '01/01/2010')

现在,我如何遍历results 中的所有条件并将每个条件链接到where 子句?

我在想类似的事情

methods.grep(/_condition$/).map { |c| where(send(c)) }

或类似的,但我不能让它工作。

有什么建议吗?

谢谢

【问题讨论】:

  • 我的解决方案中缺少的是返回关系。 methods.grep(/_condition$/).inject(Employee) do |klass, condition| klass = klass.where(send(condition)) end

标签: ruby-on-rails arel


【解决方案1】:

是的,为此使用链接。我会将您的过滤器字段放在一个数组中,例如filter[name]

然后你可以这样做:

@employees = Employee
if params[:filter]
  params[:filter].each do |f_name, f_value|
    next if f_value.blank?
    @employees = @employees.where(f_name => f_value)
  end
end

抱歉无法测试,但应该可以工作

【讨论】:

  • 不幸的是,where 子句总是相同的。有些东西是一个简单的相等,有时我需要匹配一个正则表达式,我需要检查值是否在范围内。我想做的是定义 N 个_condition 方法并循环它们。
【解决方案2】:

您的示例可以使用,但您需要将 where 子句放在关联上:

methods.grep(/_condition$/).each do |condition|
  association = association.where(send(condition))
end

【讨论】:

  • 感谢您的回复。 association 是什么?顺便说一句,上面的代码不起作用。
  • 关联是您尝试应用过滤器的范围。例如Employee.all
  • 好的。无论如何,我已经按照我上面的评论中的描述解决了它。祝你好运1
猜你喜欢
  • 2010-09-24
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多