【发布时间】: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