更新时间:2023-11-11 23:49:04
您尝试解决错误问题的方法有些偏离。您正在尝试构建一个传递给ActiveRecord的字符串,以便在您仅应尝试构建查询时就可以构建一个查询。
Your approach is a little off as you're trying to solve the wrong problem. You're trying to build a string to hand to ActiveRecord so that it can build a query when you should simply be trying to build a query.
:
Model.where('a and b')
这与说的一样:
Model.where('a').where('b')
,您可以说:
Model.where('c like ?', pattern)
而不是:
Model.where("c like '#{pattern}'")
将这两个想法与您的 self.instance_values
结合起来>您可能会得到类似的内容
Combining those two ideas with your self.instance_values
you could get something like:
def query
self.instance_values.select { |_, v| v.present? }.inject(YourModel) do |q, (name, value)|
q.where("#{name} like ?", "%#{value}%")
end
end
甚至:
def query
empties = ->(_, v) { v.blank? }
add_to_query = ->(q, (n, v)) { q.where("#{n} like ?", "%#{v}%") }
instance_values.reject(&empties)
.inject(YourModel, &add_to_query)
end
那些假设您已经正确地将所有实例变量列入了白名单。如果还没有,那么应该。
Those assume that you've properly whitelisted all your instance variables. If you haven't then you should.