我正试图在Rails5应用上实现一个简单的搜索引擎。撰写SQL查询
基本上,我有一个窗体中的几个字段,我需要获取匹配所有输入值的所有记录。请注意,所有值都是可选的。
我可以搜索的值是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' – macsig