Polymorphic associations’ as and where is used in SQL

Problem

You are using a polymorphic association in your application, and you would like to know how exactly the as declaration in your model has_many is used in the SQL by ActiveRecord. So following the example in the Rails Guides with the following models:

 

Solution

ActiveRecord uses the as in the model declaration as a guide to find the foreign id key in the polymorphic association, by adding the _id to the :as name. So following the
example above the query for the product would be: