如何使用 activerecord 参数化数组

How to parameterized array with activerecord

A​​ctiverecord 为基本类型生成参数化查询,但是,它确实参数化数组类型。

例如

Article.where(id: 1) 
# generates
# SELECT "articles".* FROM "articles" WHERE "articles"."id" =   [["id", 1]]

但是,

Article.where(id: [1,2])
# generates
# SELECT "articles".* FROM "articles" WHERE "articles"."id" IN (1, 2)
# rather than
# SELECT "articles".* FROM "articles" WHERE "articles"."id" IN (, )
  [["id", 1], ["id", 2],]

是否可以重组查询或使用 Arel 为 IN 子句生成参数化查询?

无法找到开箱即用的东西,因此,我实现了 where 运算符的专门版本,它为 <>in 和原始区域条件生成参数化查询, 如果需要,应该很容易添加对更多运算符的支持..

https://github.com/faisalmansoor/activerecord-extensions

Post.where_gt(:likes, 10).to_a
# will generate
# SELECT "posts".* FROM "posts" WHERE ("posts"."likes" > ?)
# [["likes", 10]]

Post.where_lt(:likes, 10).to_a
# will generate
# SELECT "posts".* FROM "posts" WHERE ("posts"."likes" < ?)
# [["likes", 10]]

Post.where_in(:likes, [2,3,4]).pluck(:title).to_a
# will generate
# SELECT "posts"."title" FROM "posts" WHERE "posts"."likes" IN (?, ?, ?)
# [["likes", 2], ["likes", 3], ["likes", 4]]


clause = Post.arel_table[:title].
  eq(Arel::Nodes::BindParam.new).
  or(Post.arel_table[:likes].gt(Arel::Nodes::BindParam.new))

Post.where_with_bind(clause, {title: 'Good Title', likes: 10}).to_a

# will generate
# SELECT "posts".* FROM "posts" WHERE ("posts"."title" = ? OR "posts"."likes" > ?)
# [["title", "Good Title"], ["likes", 10]]