当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - How to invoke a postgres function using arel?

问题描述:

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

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.

Any thoughts on how to accomplish this would be appreciated.

网友答案:

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:

# == 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";
分享给朋友:
您可能感兴趣的文章:
随机阅读: