【问题标题】:Arel: How to write attr = NULL in arel speak?Arel:如何在 arel speak 中写 attr = NULL?
【发布时间】:2012-10-15 13:50:30
【问题描述】:

我对 arel 有疑问:我想使用 Arel 强制执行类似“attr = NULL”的操作。 Arel 允许我做这样的事情:

table = obj.arel_table # obj has attr
table[:attr].eq(nil) # returns ''objs'.'attr' IS NULL'

这是公平的,因为在查询中这是正确的做法。但是在更新时,我希望能够将某些内容设置为 NULL,并且最好不必自己编写 SQL(AR 中的 update_all 不支持集合上的类似 ARel 的功能:objs.things.update_all(:created_at => nil )。这打破了)。我基本上是在尝试在 update_all 调用中重复执行 arel 和 to_sql 功能的代码块。这可能吗?

【问题讨论】:

  • 您确定 created_at 列允许空值吗?你的例子到底是怎么破的?

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


【解决方案1】:

您只需将nil 传递给eq

table[attr].eq(nil)

生成where attr is not null

【讨论】:

    【解决方案2】:

    我知道做这样的事情的唯一方法是使用 SqlLiteral 类似:

    table[attr].eq(Arel::Nodes::SqlLiteral.new("NULL"))
    

    这将迫使 arel 跳过 nil 的处理器并进行简单的相等

    【讨论】:

    • 这会产生= NULL,而不是IS NULL
    猜你喜欢
    • 2020-05-15
    • 1970-01-01
    • 2011-05-13
    • 2011-09-06
    • 2011-04-25
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多