Skip to content

Instantly share code, notes, and snippets.

@patshaughnessy
Last active August 29, 2015 14:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patshaughnessy/81b40188214259678541 to your computer and use it in GitHub Desktop.
Save patshaughnessy/81b40188214259678541 to your computer and use it in GitHub Desktop.
A quick look at when ActiveRecord instantiates Ruby objects
With regard to this twitter conversation:
https://twitter.com/PericlesTheo/status/601745115074420736
Hi Pericles,
This morning I took a quick look at how ActiveRecord converts the query result
back into Ruby objects.
Here’s where it happens:
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/querying.rb#L38
- So when you execute some query, such as Person.first or whatever,
ActiveRecord calls find_by_sql. (For some queries, such as Person.count, it
will use a different code path).
- The SQL is actually executed by connection.select_all - this converts the sql
Arel tree object into a string and sends it to the DB. It uses a different
adapter based on which DB server you are using. This is what I talked about
in the presentation.
- Then the ActiveRecord adapter for he DB you are using converts the actual
query results into an array of ActiveRecord::Result objects.
- Once that is done and select_all returns, notice that ActiveRecord calls:
result_set.map { |record| instantiate(record, column_types) }
See:
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/querying.rb#L50
- This converts each result into the actual AR class from your Rails app.
Does that make sense?
@PericlesTheo
Copy link

Makes perfect sense! Thanks for taking the time to answer my question. Really appreciate it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment