【问题标题】:How to use Arel methods like `coalesce` outside Active Record?如何在 Active Record 之外使用诸如“coalesce”之类的 Arel 方法?
【发布时间】:2022-08-08 16:45:55
【问题描述】:

我想在 Active Record 模型之外生成部分查询,例如

class Foo
  def to_arel
    coalesce(1, 2)
  end
end

我可以通过一些现有的模型,但这并不优雅:

Item.arel_table.coalesce(1, 2).to_sql # => \"COALESCE(1, 2)\"

有什么更好的方法?

(这个项目目前在 Rails 6.1 上,但我对新版本的解决方案也很感兴趣。)

    标签: ruby-on-rails arel


    【解决方案1】:

    这就是我想出的:

    class Foo
      def to_arel
        arel.coalesce(1, 2)
      end
    
      private
    
      def arel
        @arel ||= Class.new.tap { _1.extend Arel::FactoryMethods }
      end
    end
    

    我也可以直接在Fooinclude 它,但这对我来说似乎很乱。

    【讨论】:

      猜你喜欢
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多