gpt4 book ai didi

ruby - 使用 ActiveRecord 插入时如何使用 SQL 函数?

转载 作者:太空宇宙 更新时间:2023-11-03 16:27:03 31 4
gpt4 key购买 nike

Sequel , 在插入行之前很容易应用函数:

the_geom_nosrid = Sequel.function :ST_GeomFromText, params[:the_geom]
the_geom_4326 = Sequel.function :ST_SetSRID, the_geom_nosrid, 4326
the_geom_900913 = Sequel.function :ST_Transform, the_geom_4326, 900913

DB[:drawings].returning(:id).insert the_geom: the_geom_900913

这会导致像这样的查询

INSERT INTO drawings(the_geom) VALUES (ST_Transform(ST_SetSRID(ST_GeomFromText(...), 4326), 900913))

当我使用 ActiveRecord 插入时如何应用 SQL 函数?这不起作用:

class Drawing < ActiveRecord::Base
before_create do
the_geom_nosrid = Arel::Nodes::NamedFunction.new('ST_GeomFromText', [the_geom])
the_geom_4326 = Arel::Nodes::NamedFunction.new('ST_SetSRID', [the_geom_nosrid, 4326])
the_geom_900913 = Arel::Nodes::NamedFunction.new('ST_Transform', [the_geom_4326, 900913])

# doesn't work: `Type Error: can't cast Arel::Nodes::NamedFunction to `
# self.the_geom = the_geom_900913

# doesn't work: tries to insert the text "ST_Transform(ST_SetSR..." into a geometry column
# self.the_geom = Arel.sql(the_geom_900913.to_sql)
end
end

最佳答案

用惊人的 scuttle.io 解决了:

Drawing.create(
:the_geom => Arel::Nodes::NamedFunction.new(
'ST_Transform', [
Arel::Nodes::NamedFunction.new(
'ST_SetSRID', [
Arel::Nodes::NamedFunction.new('ST_GeomFromText', ['foobar']), 4326
]
), 900913
]
)
)

关于ruby - 使用 ActiveRecord 插入时如何使用 SQL 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770505/

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