如何使用arel调用postgres函数?

时间:2022-09-11 17:31:30

I have a Postgres function called 'move_to_end' that I'm invoking using find_by_sql as below:

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

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

I'd like to replace the find_by_sql statement with an arel call, but all the examples I've found require arel to work with a table.

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

Any thoughts on how to accomplish this would be appreciated.

任何关于如何实现这一目标的想法都会受到赞赏。

1 个解决方案

#1


2  

You can do it by using NamedFunctions in Arel. However, you still have to use arel_table to reference table column in the query. One possible workaround is to alias it with underscore:

可以在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";

#1


2  

You can do it by using NamedFunctions in Arel. However, you still have to use arel_table to reference table column in the query. One possible workaround is to alias it with underscore:

可以在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";