Hello. Is it possible to get raw sql query result from ActiveRecord::Relation ?
Now I can make it this way:
> ```
> sql = Note.select('count(*), commit_id').group(:commit_id).to_sql
> ```
> ActiveRecord::Base.connection.execute(sql).to_a
Should that mimick the low-level API? select_value, select_rows, etc?
On the other hand I feel Arel and #to_sql are out of hand. In the beginning
this was considered to be private to AR (this was certainly the point of
view of Pratik, who implemented the initial integration IIRC). AR could
change completely Arel with something else in theory as long as the public
interface was respected.
#to_sql + #execute is widely used, because it’s a legitimate, and popular use case. Sometimes, we just need pure ruby objects. AR models become an overhead in those situations.
I was discussing with Aaron and we believe that passing relations to these methods should not be advised. This is why we want to add a method to relation to get the low level values.
#to_sql + #execute is widely used, because it's a legitimate, and popular
use case. Sometimes, we just need pure ruby objects. AR models become an
overhead in those situations.
AR::Base#connection and its API are totally public, but #to_sql wasn't
intended to be. AR is not a SQL builder, it is a layer between Ruby and
databases.
That's why guides have never covered Arel etc., those are tools used by AR
to build SQL *internally*, not to be exposed to end-users.
I'd bet #to_sql ended up in api.rubyonrails.org because nobody nodoc'ed it,
I doubt it was intentional.
I’d like a way to work with raw data as it was returned by a SQL query. Mostly because Rails’ eager loading has a penchant for not working with ActiveRecord::QueryMethods.select, losing useful data in the process.
As for Arel and #to_sql… Why wasn’t it made public? Consider that ActiveRecord doesn’t even have a convenient interface for writing greater than/less than queries. Arel could be an answer to this problem, and more.