learning_to_swim
learning_to_swim

Reputation: 361

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.

For example,

  1. It is considered a good practice in SQL to order the tables in your query from smallest to largest. 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.

    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.

Thanks!

Upvotes: 3

Views: 2402

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176372

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.

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.

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.

My suggestion is to avoid doing that for queries that can easily be reproduced in ActiveRecord and AREL.

Upvotes: 9

Related Questions