【问题标题】:How to invoke a postgres function using arel?如何使用 arel 调用 postgres 函数?
【发布时间】:2014-12-14 20:06:00
【问题描述】:

我有一个名为“move_to_end”的 Postgres 函数,我正在使用 find_by_sql 调用它,如下所示:

def move_to_end
  self.class.find_by_sql ["select move_to_end(?)", id]
end

我想用 arel 调用替换 find_by_sql 语句,但我找到的所有示例都需要 arel 才能使用表。

任何关于如何实现这一点的想法将不胜感激。

【问题讨论】:

  • 我觉得像Arel::Nodes::SqlLiteral.new('select move_to_end...')

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


【解决方案1】:

您可以通过在 Arel 中使用 NamedFunctions 来实现。 但是,您仍然必须使用 arel_table 来引用查询中的表列。一种可能的解决方法是使用下划线对其进行别名:

# == Schema Information
#
# Table name: solution
#
#  solution_id    :integer          not null, primary key
#  body    :text
#
class Solution
  class << self
    alias_method :_, :arel_table

    def only_checked
        _.project(checked(_[:solution_id]))
    end

    def checked
        Arel::Nodes::NamedFunction.new('CHECKED', [query])
    end
  end
end 

Solution.only_checked.to_sql # -> SELECT CHECKED("solution"."solution_id") FROM "solution";

【讨论】:

  • 那行得通……不得不重新安排 postgres 函数。谢谢!
猜你喜欢
  • 2010-10-08
  • 2012-03-07
  • 2017-11-25
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
相关资源
最近更新 更多