【发布时间】:2020-01-30 19:14:08
【问题描述】:
我们正在 ruby on rails 中实现过滤器,过滤器可以与 AND/OR 条件结合使用。
实现过滤条件之间的OR
过滤器 1 OR 过滤器 1 OR 过滤器 3 = 我们通过将两个活动记录关系与 OR 结合使用 rails 或方法 (https://blog.bigbinary.com/2016/05/30/rails-5-adds-or-support-in-active-record.html) 实现了这一点。
例如:过滤条件为,
id is 1 or id is 2
为了达到这个目的,
Person.where(id: 1).or(Person.where(id: 2)
产生的查询将是,SELECT "people".* FROM "people" WHERE ("people"."id" = $1 OR "people"."id" = $2) [["id", 1], ["id", 2]]
实现过滤条件之间的AND
我们面临的主要问题是将过滤器与AND条件结合起来,
id is 1 AND id is 2
我们尝试使用merge method in rails,但使用该方法,相同的条件将被最新的条件覆盖。也找到了这个rails issue
Person.where(id:1).merge(Person.where(id:2))
# The first condition is overridden by second, if the same condition is on the same column.
Person Load (0.7ms) SELECT "people".* FROM "people" WHERE "people"."id" = $1 [["id", 2]]
注意:我提供的示例可能看起来很简单,但过滤器逻辑确实很复杂,因此我们不能只在其中链接 rails 范围。
((id is 1 or id is 2) AND (id is 10 or id is 20))
这就是一个简单过滤器的样子。可以添加更多的复杂性。我们的过滤器看起来像ransack demo app。
我们要做的是用 OR 组合所有内部块,用 AND 组合所有外部块。如果过滤条件是 AND 并且要在同一列中查询该列,有人可以提出更好的方法吗?
提前致谢。
我们还考虑获取 where 条件并进行字符串连接。但希望这是最坏的情况。
【问题讨论】:
标签: ruby-on-rails activerecord filter ruby-on-rails-5