凌乱的轨道模型或



我想在我的模型集合中做很多WHERE,在作用域上有OR和参数。

需要此.where('1=1'),因为这样OR不起作用。

我的messy代码如下所示:

scope :search, ->(params) {
patients = all.where('1=1') # Please pay attention here!
if terms = params[:search].presence
terms.split('|').each do |term|
patients =  patients.or(
Patient.where
'name LIKE :like OR ' +
'surname_1 LIKE :like OR ' +
'surname_2 LIKE :like OR ' +
'email LIKE :like OR ' +
'identifier_number = :equals OR ' +
'history = :equals OR ' +
'CAST(telephone_1 AS char) LIKE :like OR ' +
'CAST(telephone_2 AS char) LIKE :like ',
like:   "%#{ term }%",
equals: term)
end
end

有一种方法可以避免#2行上的这种.where('1=1')

有其他方法可以做到这一点吗?

您可以使用.none方法,至少比这个技巧干净一些。

返回具有零条记录的可链接关系。

返回的关系实现空对象模式。这是一个 具有定义的 null 行为的对象,并且始终返回一个空数组 不查询数据库的记录。

链接到返回关系的任何后续条件都将 继续生成空关系,并且不会触发任何查询 数据库。

用于方法或范围可以返回零条记录但 结果需要可链接。

patients = Patient.none

或者如果您想在没有搜索参数的情况下将它们全部返回

patients = Patient.all

使用

scoped = Patient.where({})
scoped = scoped.or( Patient.where({...}) )

最新更新