简体   繁体   English

Rails - find_by_sql vs活动记录查询

[英]Rails - find_by_sql vs active record querying

I would like to use the find_by_sql method in place of the active record query interface because of the flexibility I get in writing my own SQL. 我想使用find_by_sql方法代替活动记录查询接口,因为我在编写自己的SQL时具有灵活性。

For example, 例如,

  1. It is considered a good practice in SQL to order the tables in your query from smallest to largest. 在SQL中,将查询中的表从最小到最大排序,这被认为是一种很好的做法。 When using the active record query interface, you will have to start with the result model which could be the largest table. 使用活动记录查询界面时,您必须从可能是最大表的结果模型开始。

  2. I can also easily avoid the N+1 problem by including the target table in the join itself and including the required columns from multiple tables. 我还可以通过在连接本身中包含目标表并包含多个表中所需的列来轻松避免N + 1问题。

    I would like to know if there are reasons I should not be using the find_by_sql option, especially when I will be writing ANSI SQL that should be compatible with all, if not most databases. 我想知道是否有理由我不应该使用find_by_sql选项,特别是当我将编写ANSI SQL时,它应该与所有(如果不是大多数)数据库兼容。

Thanks! 谢谢!

Writing SQL code directly is normally not encouraged because it will prevent you from accessing features such as the lazy-execution of SQL queries and may potentially lead to invalid or unsafe queries. 通常不鼓励直接编写SQL代码,因为它会阻止您访问SQL查询的延迟执行等功能,并可能导致无效或不安全的查询。

In fact, ActiveRecord automatically converts Ruby objects into corresponding SQL statements (such as ranges into BETWEEN or arrays into IN), filters strings from SQL injections and ActiveRecord::Relations provide lazy query executions. 实际上,ActiveRecord会自动将Ruby对象转换为相应的SQL语句(例如将范围转换为BETWEEN或将数组转换为IN),从SQL注入过滤字符串,ActiveRecord :: Relations提供延迟查询执行。

That said, if you know what you are doing or using ActiveRecord would be extremely complex to achieve a specific query, there is nothing wrong to write your SQL. 也就是说,如果您知道自己在做什么或者使用ActiveRecord来实现特定查询会非常复杂,那么编写SQL就没有错。

My suggestion is to avoid doing that for queries that can easily be reproduced in ActiveRecord and AREL. 我的建议是避免对可以在ActiveRecord和AREL中轻松复制的查询执行此操作。

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

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