【问题标题】:How to parameterized array with activerecord如何使用 activerecord 参数化数组
【发布时间】:2015-10-01 17:56:18
【问题描述】:

Activerecord 为基本类型生成参数化查询,但它确实对数组类型进行了参数化。

例如

Article.where(id: 1) 
# generates
# SELECT "articles".* FROM "articles" WHERE "articles"."id" = $1  [["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 ($1, $2)
  [["id", 1], ["id", 2],]

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

【问题讨论】:

  • 什么轨道版本?因为它在 4.1 的两种情况下都生成非参数版本? gist.github.com/gaurish/be9d29d09162e2213611
  • 我尝试了最新的 Rails 版本。您不会看到带有 to_sql 的参数查询,因为它将绑定参数替换为值。尝试在 Rails 控制台中使用 ActiveRecord::Base.logger = Logger.new(STDOUT) 启用 activerecord 日志记录。

标签: sql ruby-on-rails activerecord arel parameterized


【解决方案1】:

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

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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2019-09-02
    • 1970-01-01
    相关资源
    最近更新 更多