如何使用ActiveRecord查询多个表?

时间:2015-02-07 01:05:51

标签: ruby-on-rails rails-activerecord

我试图找出如何在ActiveRecord中编写此查询的等效内容:

SELECT id FROM projects, neighborhoods
WHERE ST_WITHIN(projects.lonlat, neighorhoods.the_geom);

我尝试了几种方法,包括

Neighborhood.select(:id).from('projects').where("ST_WITHIN(projects.lonlat, neighorhoods.the_geom)")

但结果查询始终解析为单个表。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

利用神奇的工具scuttle.io to将SQL转换为Arel:

Neighborhood.select(:id).where(
  Arel::Nodes::NamedFunction.new(
    'ST_WITHIN', [
      Project.arel_table[:lonlat], Neighorhood.arel_table[:the_geom]
    ]
  )
)