简体   繁体   English

了解活动记录查询

[英]Understanding Active record Queries

I needed to do some complex subquery for a project i am working on. 我需要为我正在处理的项目做一些复杂的子查询。 I could't figure out how to do it in plain active record. 我不知道如何在简单的活动记录中做到这一点。 I tried several things and ended up opting for generic SQL query using 我尝试了几件事,最终选择使用

ActiveRecord::Base.connection.exec_query(
  "
  SELECT gid as id, (dp).path, (dp).geom, ST_AsText((dp).geom),  ST_X((dp).geom) as longitude, ST_Y((dp).geom) as latitude
  FROM (
  SELECT gid, ST_DumpPoints(ST_AsText(ST_Transform(geom, 4326))) as dp
  FROM apples
  WHERE gid in (#{@object.id})
  ) AS GEO;
  "
)

Here i am selecting from a subquery and transforming geometry to Points using plain postgresql. 在这里,我从子查询中进行选择,并使用普通的postgresql将几何转换为Point。 If i were to do it in ActiveRecord queries, how do i do it? 如果我要在ActiveRecord查询中执行此操作,该怎么办? Is this type of query even possible in ActiveRecord? 在ActiveRecord中甚至可以进行这种查询吗?

ActiveRecord does not provide you with anything fancy. ActiveRecord不会为您提供任何幻想。 You can perform simple stuff, but when there's a need for a complex query you just go with plain SQL as you did. 您可以执行简单的工作,但是当需要复杂的查询时,您只需像使用普通SQL一样就可以了。

You can check Arel which might give you more flexibility. 您可以检查Arel ,这可能会给您带来更大的灵活性。 But still, in the end, I think, it's not worth - it won't be as effective as a native query. 但是,最后,我认为这不值得-它不会像本机查询那样有效。

Do simple stuff with ORM. 用ORM做简单的事情。 Do complex stuff with plain SQL. 用普通的SQL处理复杂的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM