我们正在轨道上的红宝石中实现过滤器,并且这些过滤器可能与AND / OR条件结合使用。
为了达到过滤条件之间的OR
[过滤器1或过滤器1或过滤器3 =我们通过将两个活动记录关系与OR结合起来,使用了rails或method(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条件并进行字符串连接。但是希望那是最坏的情况。
要在过滤条件之间达到OR
和AND
,您可以简单地使用arel table。 Arel表使复杂查询更容易实现。