2016-12-21 89 views
0

我正试图在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)) } 

或相似的,但我不能使它发挥作用。

有什么建议吗?

谢谢

+0

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

回答

0

是的,为此使用链接。我会把你的过滤器中的字段阵列,例如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 

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

+0

不幸的是,where子句总是相同的。有些东西是简单的平等,有时我需要匹配正则表达式,我需要检查值是否在范围内。我想要做的是定义N'_condition'方法并循环遍历它们。 – macsig

0

你的例子会工作但您需要将where子句放在关联上:

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

感谢您的回复。什么是“关联”?顺便说一句以上代码不起作用。 – macsig

+0

关联是您尝试应用过滤器的范围。例如'Employee.all' – vegetaras

+0

好的。无论如何,我已经解决了它,如我在上面的评论中所述。有一个好的1 – macsig