gpt4 book ai didi

ruby-on-rails - 如何使用 arel 调用 postgres 函数?

转载 作者:行者123 更新时间:2023-12-04 07:37:45 25 4
gpt4 key购买 nike

我有一个名为“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 才能使用表。

如有任何关于如何实现此目的的想法,我们将不胜感激。

最佳答案

您可以使用 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";

关于ruby-on-rails - 如何使用 arel 调用 postgres 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com