2 ms·
> Make the database query using SQL directly, and then inject the results into the HTML template to be delivered to the browser. This is what I do for the most
by pmontra 4y ago
> Make the database query using SQL directly, and then inject the results into the HTML template to be delivered to the browser.
This is what I do for the most complex queries, where translating them to the ORM would be a time consuming pain. What I do normally is think in SQL and write in the ORM language. After all the API of the database is SQL, not the ORM, and I already know SQL.
In this way it's obvious that you have to write includes(:comments), because it's a join, and it's obvious that the original
object.votes.count
would generate one query each time it is called. I write the separate queries and compose the results instead. I'm not using BatchLoader or other gems. Using directly the ORM is enough.
If this query turns out to be important for the performances of the application, I'll think about a way to write it with a single query in SQL to make the database do all the work. Then translate it in ActiveRecord or leave it in SQL if it takes too long. Sometimes it's not obvious how to do it, a problem common to all ORMs of all languages.
Edit: somebody called saila gave an example of such a query in the comments one hour before I wrote my reply.
- imtringued 4y agoA lot of complex computed properties can easily be made efficient by having "WITH" statements. The with query starts with the ID of the object to which the computed property is attached to. So in this case you would do the same thing as the author and write WITH comment_vote_count as select comment_id, COUNT(vote_id) from comment left join vote ... The ORM would just treat this like a normal table and do a join based on the comment ID except the ORM provides a convenient API to do this, which it currently does not...