到目前为止,我只能运行一个find_by_sql查询,该查询涉及两个表的所有记录以查找Intersects。
Regionpolygon.where('nation_id = ?', 74).find_by_sql "SELECT regionpolygons.id, area_name, destinations.id
FROM regionpolygons, destinations
WHERE ST_Intersects(regionpolygons.polygon_area, destinations.latlon)"
需要实现的两个目标是:
@rps = Regionpolygon.where('nation_id = ?',74).all
这似乎工作..@dests = Destination.all @dests.each do |dest| [...]
提供单个点,以便迭代可以允许更新记录属性实例变量在添加到此类查询时似乎没有被很好地消化如何制定这个查询?
您的问题有点不清楚,但是您只是在寻找一种可管理的编程方式来生成该查询,那么您可以使用arel
执行此搜索,如下所示
rp_table = Regionpolygon.arel_table
destination_table = Destination.arel_table
query = rp_table.project(rp_table[:id],
rp_table[:area_name],
destination_table[:id].as('destination_id')
).join(destination_table).on(
Arel::Nodes::NamedFunction.new('ST_Intersects',
[rp_table[:polygon_area], destination_table[:latlon]]
)
).where(rp_table[:nation_id].eq(74))
这将产生以下SQL
SELECT
[regionpolygons].[id],
[regionpolygons].[area_name],
[destinations].[id] AS destination_id
FROM
[regionpolygons]
INNER JOIN [destinations] ON
ST_Intersects([regionpolygons].[polygon_area], [destinations].[latlon])
WHERE
[regionpolygons].[nation_id] = 74
你可以通过字面上调用query
将to_sql
转换为SQL。所以:
ActiveRecord::Base.connection.exec_query(query.to_sql).to_hash
将返回它发现执行上述行的Array
,其中行被转换为哈希值。这个哈希看起来像:
{"id" => 1, "area_name" => "area_name", "destination_id" => 1}