使用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
答案 0 :(得分:1)
解决了惊人的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
]
)
)